<div class="container">
  <h1 class="text-center mb-5">System Statistics</h1>
  
  <!-- Stats Overview Cards -->
  <div class="row mb-5">
    <div class="col-md-4">
      <div class="card bg-dark border-primary h-100">
        <div class="card-body text-center">
          <i class="fas fa-envelope fa-3x mb-3 text-primary"></i>
          <h3 class="card-title" id="totalMailboxes">-</h3>
          <p class="card-text">Total Mailboxes</p>
          <div class="mt-3">
            <span class="badge bg-success me-2" id="activeMailboxes">-</span> Active
            <span class="badge bg-warning ms-2" id="expiringToday">-</span> Expiring Today
          </div>
        </div>
      </div>
    </div>
    
    <div class="col-md-4">
      <div class="card bg-dark border-primary h-100">
        <div class="card-body text-center">
          <i class="fas fa-globe fa-3x mb-3 text-primary"></i>
          <h3 class="card-title" id="totalDomains">-</h3>
          <p class="card-text">Total Domains</p>
          <div class="mt-3">
            <span class="badge bg-success me-2" id="activeDomains">-</span> Active
            <span class="badge bg-danger ms-2" id="inactiveDomains">-</span> Inactive
          </div>
        </div>
      </div>
    </div>
    
    <div class="col-md-4">
      <div class="card bg-dark border-primary h-100">
        <div class="card-body text-center">
          <i class="fas fa-clock fa-3x mb-3 text-primary"></i>
          <h3 class="card-title" id="expiredMailboxes">-</h3>
          <p class="card-text">Expired Mailboxes</p>
          <div class="mt-3">
            <span class="badge bg-warning" id="expiringSoon">-</span> Expiring Soon (3 days)
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Charts Section -->
  <div class="row mb-5">
    <div class="col-lg-6 mb-4">
      <div class="card bg-dark border-primary">
        <div class="card-header bg-primary text-white">
          <h4 class="mb-0">Mailbox Creation (Last 7 Days)</h4>
        </div>
        <div class="card-body">
          <canvas id="mailboxCreationChart" height="250"></canvas>
        </div>
      </div>
    </div>
    
    <div class="col-lg-6 mb-4">
      <div class="card bg-dark border-primary">
        <div class="card-header bg-primary text-white">
          <h4 class="mb-0">Top Domains by Mailbox Count</h4>
        </div>
        <div class="card-body">
          <canvas id="topDomainsChart" height="250"></canvas>
        </div>
      </div>
    </div>
  </div>
  
  <div class="row mb-5">
    <div class="col-lg-12">
      <div class="card bg-dark border-primary">
        <div class="card-header bg-primary text-white">
          <h4 class="mb-0">Mailbox Creation (Last 30 Days)</h4>
        </div>
        <div class="card-body">
          <canvas id="monthlyCreationChart" height="250"></canvas>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Domain Details Table -->
  <div class="row">
    <div class="col-12">
      <div class="card bg-dark border-primary">
        <div class="card-header bg-primary text-white">
          <h4 class="mb-0">Domain Details</h4>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-dark table-hover">
              <thead>
                <tr>
                  <th>Domain</th>
                  <th>Description</th>
                  <th>Status</th>
                  <th>Mailbox Count</th>
                </tr>
              </thead>
              <tbody id="domainTableBody">
                <!-- Domain data will be inserted here -->
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Fetch all stats data
    Promise.all([
      fetch('https://api.2weekmail.test/stats/system').then(res => res.json()),
      fetch('https://api.2weekmail.test/stats/mailboxes').then(res => res.json()),
      fetch('https://api.2weekmail.test/stats/domains').then(res => res.json())
    ])
    .then(([systemStats, mailboxStats, domainStats]) => {
      // Update overview cards
      document.getElementById('totalMailboxes').textContent = systemStats.mailboxes.total;
      document.getElementById('activeMailboxes').textContent = systemStats.mailboxes.active;
      document.getElementById('expiringToday').textContent = systemStats.mailboxes.expiringToday;
      
      document.getElementById('totalDomains').textContent = domainStats.domains.total;
      document.getElementById('activeDomains').textContent = domainStats.domains.active;
      document.getElementById('inactiveDomains').textContent = domainStats.domains.inactive;
      
      document.getElementById('expiredMailboxes').textContent = mailboxStats.expiryStats.expired;
      document.getElementById('expiringSoon').textContent = mailboxStats.expiryStats.expiringSoon;
      
      // Create charts
      createMailboxCreationChart(systemStats.creationStats);
      createTopDomainsChart(domainStats.topDomains);
      createMonthlyCreationChart(mailboxStats.creationByDay);
      
      // Populate domain table
      populateDomainTable(domainStats.domainDetails);
    })
    .catch(error => {
      console.error('Error fetching stats:', error);
      alert('Failed to load statistics. Please try again later.');
    });
  });
  
  function createMailboxCreationChart(data) {
    const ctx = document.getElementById('mailboxCreationChart').getContext('2d');
    
    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: data.map(item => item.date),
        datasets: [{
          label: 'Mailboxes Created',
          data: data.map(item => item.mailboxesCreated),
          backgroundColor: 'rgba(13, 110, 253, 0.7)',
          borderColor: 'rgba(13, 110, 253, 1)',
          borderWidth: 1
        }]
      },
      options: {
        responsive: true,
        scales: {
          y: {
            beginAtZero: true,
            ticks: {
              precision: 0
            }
          }
        },
        plugins: {
          legend: {
            display: false
          }
        }
      }
    });
  }
  
  function createTopDomainsChart(data) {
    const ctx = document.getElementById('topDomainsChart').getContext('2d');
    
    new Chart(ctx, {
      type: 'pie',
      data: {
        labels: data.map(item => item.domain),
        datasets: [{
          data: data.map(item => item.count || item.mailboxCount),
          backgroundColor: [
            'rgba(13, 110, 253, 0.7)',
            'rgba(25, 135, 84, 0.7)',
            'rgba(220, 53, 69, 0.7)',
            'rgba(255, 193, 7, 0.7)',
            'rgba(13, 202, 240, 0.7)',
            'rgba(111, 66, 193, 0.7)',
            'rgba(253, 126, 20, 0.7)',
            'rgba(32, 201, 151, 0.7)',
            'rgba(108, 117, 125, 0.7)',
            'rgba(248, 249, 250, 0.7)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: {
            position: 'right'
          }
        }
      }
    });
  }
  
  function createMonthlyCreationChart(data) {
    const ctx = document.getElementById('monthlyCreationChart').getContext('2d');
    
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: data.map(item => item.date),
        datasets: [{
          label: 'Mailboxes Created',
          data: data.map(item => item.count),
          backgroundColor: 'rgba(13, 110, 253, 0.1)',
          borderColor: 'rgba(13, 110, 253, 1)',
          borderWidth: 2,
          tension: 0.3,
          fill: true
        }]
      },
      options: {
        responsive: true,
        scales: {
          y: {
            beginAtZero: true,
            ticks: {
              precision: 0
            }
          }
        }
      }
    });
  }
  
  function populateDomainTable(domains) {
    const tableBody = document.getElementById('domainTableBody');
    
    domains.forEach(domain => {
      const row = document.createElement('tr');
      
      const domainCell = document.createElement('td');
      domainCell.textContent = domain.domain;
      
      const descriptionCell = document.createElement('td');
      descriptionCell.textContent = domain.description || 'N/A';
      
      const statusCell = document.createElement('td');
      const statusBadge = document.createElement('span');
      statusBadge.className = domain.active ? 'badge bg-success' : 'badge bg-danger';
      statusBadge.textContent = domain.active ? 'Active' : 'Inactive';
      statusCell.appendChild(statusBadge);
      
      const countCell = document.createElement('td');
      countCell.textContent = domain.mailboxCount;
      
      row.appendChild(domainCell);
      row.appendChild(descriptionCell);
      row.appendChild(statusCell);
      row.appendChild(countCell);
      
      tableBody.appendChild(row);
    });
  }
</script>
