document.addEventListener('DOMContentLoaded', function () {
  async function loadActivityLogs() {
    try {
      const response = await fetch((window.APP_BASE || '') + '/activity_logs.php', { method: 'GET' });
      const data = await response.json();

      const tbody = document.getElementById('transaction-body');
      const cardContainer = document.getElementById('activity-cards-container');
      tbody.innerHTML = '';
      cardContainer.innerHTML = '';

      if (data.status !== 'success' || !data.data || data.data.length === 0) {
        const noDataMessage = `
          <tr>
            <td colspan="5" class="text-center text-muted py-4">No activity logs found</td>
          </tr>
        `;
        const noCardMessage = `
          <div class="text-center text-muted py-4">No activity logs found</div>
        `;
        tbody.insertAdjacentHTML('beforeend', noDataMessage);
        cardContainer.insertAdjacentHTML('beforeend', noCardMessage);
        return;
      }

      const logs = data.data;

      logs.forEach(log => {
          let typeIcon = '';
          let typeText = '';
          let badgeClass = 'bg-warning';
          let statusLabel = 'Pending';
        
          // Normalize status using a reliable field (use `log.status` if it exists)
          let normalizedStatus = log.status ? log.status.toLowerCase() : log.action_type.toLowerCase();
        
          if (normalizedStatus.includes('approved')) {
            badgeClass = 'bg-success';
            statusLabel = 'Approved';
          } else if (normalizedStatus.includes('pending')) {
            badgeClass = 'bg-warning';
            statusLabel = 'Pending';
          } else if (normalizedStatus.includes('declined') || normalizedStatus.includes('rejected')) {
            badgeClass = 'bg-danger';
            statusLabel = 'Declined';
          } else {
            badgeClass = 'bg-secondary';
            statusLabel = 'Info';
          }
        
          // Determine the action type for icon and label
          if (log.action_type.includes('deposit')) {
            typeIcon = '<i class="bi bi-download text-primary me-1"></i>';
            typeText = 'Deposit';
          } else if (log.action_type.includes('withdrawal')) {
            typeIcon = '<i class="bi bi-upload text-danger me-1"></i>';
            typeText = log.action_type === 'admin_withdrawal' ? 'Admin Withdrawal' : 'Withdrawal';
          } else if (log.action_type === 'admin_credit') {
            typeIcon = '<i class="bi bi-plus-circle text-success me-1"></i>';
            typeText = 'Credit';
            badgeClass = 'bg-success';
            statusLabel = 'Approved';
          } else if (log.action_type === 'investment') {
            typeIcon = '<i class="bi bi-cash-stack text-info me-1"></i>';
            typeText = 'Investment';
            badgeClass = 'bg-info';
            statusLabel = 'Approved';
          } else {
            typeIcon = '<i class="bi bi-info-circle text-secondary me-1"></i>';
            typeText = 'Other';
          }
        
          const amountMatch = log.description.match(/\$\d{1,3}(,\d{3})*(\.\d{1,2})?/);
          const amountText = amountMatch ? amountMatch[0] : '-';
        
          const dateObj = new Date(log.created_at);
          const options = {
            year: 'numeric', month: 'long', day: 'numeric',
            hour: '2-digit', minute: '2-digit'
          };
          const formattedDate = dateObj.toLocaleString('en-US', options);
        
          const rowHTML = `
            <tr>
              <td>${typeIcon} ${typeText}</td>
              <td>${log.description}</td>
              <td>${amountText}</td>
              <td><span class="badge ${badgeClass}">${statusLabel}</span></td>
              <td>${formattedDate}</td>
            </tr>
          `;
        
          const cardHTML = `
            <div class="card mb-2 p-3 shadow-sm rounded-4">
              <div class="d-flex justify-content-between align-items-center">
                <strong>${typeText}</strong>
                <span class="badge ${badgeClass}">${statusLabel}</span>
              </div>
              <p class="mb-1 text-muted">${log.description}</p>
              <small class="text-secondary">${amountText} • ${formattedDate}</small>
            </div>
          `;
        
          tbody.insertAdjacentHTML('beforeend', rowHTML);
          cardContainer.insertAdjacentHTML('beforeend', cardHTML);
        });


    } catch (error) {
      console.error('Error loading activity logs:', error);
    }
  }

  window.addEventListener('DOMContentLoaded', loadActivityLogs);
});
