/* ===== ZA-FARM-KH Admin Panel JS ===== */
const API = '/zapi';
const token = localStorage.getItem('zafarm_token');
const me = JSON.parse(localStorage.getItem('zafarm_user') || '{}');

// Init UI
document.getElementById('sbUname').textContent = me.username || 'Admin';
document.getElementById('sbUemail').textContent = me.email || '';
document.getElementById('sbAvatar').textContent = (me.username || 'A')[0].toUpperCase();

// Mobile sidebar
document.getElementById('menuToggle').onclick = function() {
  document.getElementById('sidebar').classList.toggle('open');
  document.getElementById('overlayBg').classList.toggle('open');
};
document.getElementById('overlayBg').onclick = function() {
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('overlayBg').classList.remove('open');
};
document.getElementById('logoutBtn').onclick = function() {
  localStorage.removeItem('zafarm_token');
  localStorage.removeItem('zafarm_user');
  window.location.replace('/login');
};

// API helper
async function apiFetch(path, opts) {
  opts = opts || {};
  var r = await fetch(API + path, Object.assign({
    headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' }
  }, opts));
  if (r.status === 401 || r.status === 403) {
    toast('Session expired or unauthorized. Redirecting...', true);
    setTimeout(function() {
      localStorage.removeItem('zafarm_token');
      localStorage.removeItem('zafarm_user');
      window.location.replace('/login');
    }, 1500);
    throw new Error('Unauthorized');
  }
  if (!r.ok) { var err = await r.text(); throw new Error(err); }
  return r.json();
}

// Toast
function toast(msg, isErr) {
  var t = document.getElementById('toast');
  t.textContent = msg;
  t.className = 'toast show ' + (isErr ? 'err' : 'ok');
  setTimeout(function(){ t.className = 'toast'; }, 3000);
}

// Tab switch
function switchTab(tab) {
  document.querySelectorAll('section[id^="tab-"]').forEach(function(s){ s.style.display = 'none'; });
  document.querySelectorAll('.nav-item[data-tab]').forEach(function(n){ n.classList.remove('active'); });
  document.getElementById('tab-' + tab).style.display = '';
  var navEl = document.querySelector('.nav-item[data-tab="' + tab + '"]');
  if (navEl) navEl.classList.add('active');
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('overlayBg').classList.remove('open');
  if (tab === 'dashboard') loadDashboard();
  else if (tab === 'live') loadLive();
  else if (tab === 'orders') loadOrders(1);
  else if (tab === 'users') loadUsers();
  else if (tab === 'topbuyers') loadTopBuyers();
  else if (tab === 'revenue') loadRevenue();
}

// Helpers
function timeAgo(d) {
  var sec = Math.floor((Date.now() - new Date(d)) / 1000);
  if (sec < 60) return sec + ' seg ago';
  if (sec < 3600) return Math.floor(sec/60) + ' min ago';
  if (sec < 86400) return Math.floor(sec/3600) + ' hr ago';
  return Math.floor(sec/86400) + ' days ago';
}
function fmtDate(d) {
  if (!d) return '--';
  return new Date(d).toLocaleString('en-GB', {day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'});
}
function fmtMoney(v) { return '$' + parseFloat(v || 0).toFixed(3); }
function serviceIcon(s) {
  if (!s) return '📦';
  s = s.toLowerCase();
  if (s.indexOf('gmail') >= 0 || s.indexOf('mail') >= 0) return '📧';
  if (s.indexOf('phone') >= 0 || s.indexOf('sms') >= 0) return '📱';
  return '📦';
}
function statusPill(s) {
  var map = { completed:'completed', success:'completed', pending:'pending', processing:'processing', failed:'failed', cancelled:'failed' };
  var cls = map[(s||'').toLowerCase()] || 'pending';
  var labels = { completed:'Done', pending:'Pending', processing:'Processing', failed:'Failed' };
  return '<span class="pill ' + cls + '">' + (labels[cls] || s) + '</span>';
}

// Bar chart
function drawBarChart(containerId, data) {
  var el = document.getElementById(containerId);
  if (!data || !data.length) { el.innerHTML = '<span style="color:var(--text-muted);font-size:12px">No data</span>'; return; }
  var maxV = Math.max.apply(null, data.map(function(d){ return parseFloat(d.revenue||0); }).concat([0.001]));
  el.innerHTML = data.map(function(d) {
    var v = parseFloat(d.revenue || 0);
    var pct = (v / maxV * 90).toFixed(1);
    var lbl = d.date ? new Date(d.date).toLocaleDateString('en-GB',{day:'2-digit',month:'short'}) : '--';
    return '<div class="bar-col"><div class="bar-val">$' + v.toFixed(2) + '</div><div class="bar-fill" style="height:' + pct + '%"></div><div class="bar-label">' + lbl + '</div></div>';
  }).join('');
}

// Dashboard
async function loadDashboard() {
  try {
    var results = await Promise.all([apiFetch('/admin/stats'), apiFetch('/admin/revenue'), apiFetch('/admin/live')]);
    var stats = results[0], rev = results[1], live = results[2];
    document.getElementById('statUsers').textContent = stats.totalUsers || 0;
    document.getElementById('statTodayRev').textContent = '$' + (rev.today||0).toFixed(3);
    document.getElementById('statTotalOrders').textContent = stats.totalOrders || 0;
    document.getElementById('statTodayOrders').textContent = stats.todayOrders || 0;
    document.getElementById('statBalance').textContent = '$' + (rev.userBalanceTotal||0).toFixed(2);
    document.getElementById('statPending').textContent = '$' + (rev.pending||0).toFixed(3);
    drawBarChart('revenueChart', rev.daily || []);
    renderLiveFeed('dashLiveFeed', live.slice(0, 8));
  } catch(e) { toast('Error loading dashboard: ' + e.message, true); }
}

// Live feed
function renderLiveFeed(cid, rows) {
  var el = document.getElementById(cid);
  if (!rows || !rows.length) { el.innerHTML = '<div class="loading-msg">No orders yet</div>'; return; }
  el.innerHTML = rows.map(function(r) {
    var dot = r.status === 'completed' ? 'green' : r.status === 'pending' ? 'amber' : r.status === 'processing' ? 'blue' : 'red';
    var userId = r.userId || '';
    return '<div class="live-item">' +
      '<div class="live-dot ' + dot + '"></div>' +
      '<div class="live-info"><div class="live-title">' + serviceIcon(r.service) + ' ' + (r.service||'--') + ' x' + (r.qty||1) + '</div>' +
      '<div class="live-sub">&#128100; <span class="user-link" onclick="openUserModal(\'' + userId + '\')">' + (r.username||'Unknown') + '</span> &bull; ' + (r.email||'') + '</div></div>' +
      '<div style="text-align:right"><div class="live-amount">' + fmtMoney(r.total) + '</div><div class="live-time">' + timeAgo(r.createdAt) + '</div></div>' +
      '</div>';
  }).join('');
  document.getElementById('liveBadge').textContent = rows.length;
}

async function loadLive() {
  try { var data = await apiFetch('/admin/live'); renderLiveFeed('liveFeed', data); }
  catch(e) { toast('Error: ' + e.message, true); }
}
setInterval(function() {
  var lt = document.getElementById('tab-live');
  if (lt && lt.style.display !== 'none') loadLive();
}, 15000);

// Orders
var ordersPage = 1;
async function loadOrders(page) {
  page = page || 1; ordersPage = page;
  var search = (document.getElementById('orderSearch').value || '').trim();
  document.getElementById('ordersBody').innerHTML = '<tr class="loading-row"><td colspan="8"><span class="spinner"></span>Loading...</td></tr>';
  try {
    var data = await apiFetch('/admin/orders?limit=20&page=' + page + '&search=' + encodeURIComponent(search));
    var tbody = document.getElementById('ordersBody');
    if (!data.orders || !data.orders.length) {
      tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">No orders found</td></tr>';
    } else {
      tbody.innerHTML = data.orders.map(function(o) {
        return '<tr>' +
          '<td class="mono">' + (o.id||'').substring(0,8) + '&hellip;</td>' +
          '<td><span class="user-link" onclick="openUserModal(\'' + (o.userId||'') + '\')">' + (o.username||'--') + '</span><br><span style="font-size:10px;color:var(--text-muted)">' + (o.email||'') + '</span></td>' +
          '<td>' + serviceIcon(o.service) + ' ' + (o.service||'--') + '</td>' +
          '<td>' + (o.qty||1) + '</td>' +
          '<td style="color:var(--green);font-weight:700">' + fmtMoney(o.total) + '</td>' +
          '<td>' + statusPill(o.status) + '</td>' +
          '<td style="font-size:11px;color:var(--text-muted)">' + fmtDate(o.createdAt) + '</td>' +
          '<td><button class="filter-btn" style="padding:4px 10px;font-size:11px" onclick="openUserModal(\'' + (o.userId||'') + '\')">View</button></td>' +
          '</tr>';
      }).join('');
    }
    // Pagination
    var pages = Math.ceil((data.total||0) / 20);
    var pag = '';
    if (pages > 1) {
      pag += '<button class="page-btn" onclick="loadOrders(' + (page-1) + ')" ' + (page<=1?'disabled':'') + '>Prev</button>';
      for (var p = Math.max(1,page-2); p <= Math.min(pages,page+2); p++) {
        pag += '<button class="page-btn' + (p===page?' active':'') + '" onclick="loadOrders(' + p + ')">' + p + '</button>';
      }
      pag += '<button class="page-btn" onclick="loadOrders(' + (page+1) + ')" ' + (page>=pages?'disabled':'') + '>Next</button>';
    }
    document.getElementById('ordersPagination').innerHTML = pag;
  } catch(e) { toast('Error: ' + e.message, true); }
}
document.getElementById('orderSearch').addEventListener('keydown', function(e){ if(e.key==='Enter') loadOrders(1); });

// Users
var allUsers = [];
async function loadUsers() {
  document.getElementById('usersBody').innerHTML = '<tr class="loading-row"><td colspan="7"><span class="spinner"></span>Loading...</td></tr>';
  try { allUsers = await apiFetch('/admin/users'); renderUsers(allUsers); }
  catch(e) { toast('Error: ' + e.message, true); }
}
function filterUsers() {
  var q = (document.getElementById('userSearch').value||'').toLowerCase();
  renderUsers(allUsers.filter(function(u){ return (u.username||'').toLowerCase().indexOf(q)>=0 || (u.email||'').toLowerCase().indexOf(q)>=0; }));
}
document.getElementById('userSearch').addEventListener('input', filterUsers);
function renderUsers(users) {
  var tbody = document.getElementById('usersBody');
  if (!users.length) { tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:30px;color:var(--text-muted)">No users found</td></tr>'; return; }
  tbody.innerHTML = users.map(function(u, i) {
    return '<tr>' +
      '<td style="color:var(--text-muted);font-size:11px">' + (i+1) + '</td>' +
      '<td><div style="display:flex;align-items:center;gap:8px">' +
        '<div style="width:28px;height:28px;border-radius:50%;background:var(--purple-gradient);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:11px;flex-shrink:0">' + (u.username||'?')[0].toUpperCase() + '</div>' +
        '<span class="user-link" onclick="openUserModal(\'' + u.id + '\')">' + (u.username||'--') + '</span>' +
        '</div></td>' +
      '<td style="font-size:12px;color:var(--text-muted)">' + (u.email||'--') + '</td>' +
      '<td style="color:var(--green);font-weight:700">' + fmtMoney(u.balance) + '</td>' +
      '<td>' + statusPill(u.role === 'admin' ? 'processing' : 'pending').replace(/>.*</, '>' + (u.role||'user') + '<') + '</td>' +
      '<td style="font-size:11px;color:var(--text-muted)">' + fmtDate(u.createdAt) + '</td>' +
      '<td><button class="filter-btn" style="padding:4px 10px;font-size:11px" onclick="openUserModal(\'' + u.id + '\')">Manage</button></td>' +
      '</tr>';
  }).join('');
}

// Top Buyers
async function loadTopBuyers() {
  document.getElementById('topBuyersList').innerHTML = '<div class="loading-msg"><span class="spinner"></span>Loading...</div>';
  try {
    var buyers = await apiFetch('/admin/top-buyers');
    if (!buyers.length) { document.getElementById('topBuyersList').innerHTML = '<div class="loading-msg">No data yet</div>'; return; }
    document.getElementById('topBuyersList').innerHTML = buyers.map(function(b, i) {
      var rc = i===0?'rank-1':i===1?'rank-2':i===2?'rank-3':'rank-n';
      return '<div class="buyer-item" onclick="openUserModal(\'' + b.id + '\')">' +
        '<div class="buyer-rank ' + rc + '">' + (i+1) + '</div>' +
        '<div class="buyer-info"><div class="buyer-name">' + (b.username||'--') + '</div><div class="buyer-email">' + (b.email||'--') + '</div></div>' +
        '<div class="buyer-stats"><div class="buyer-spent">' + fmtMoney(b.totalSpent||0) + '</div><div class="buyer-orders">' + (b.orderCount||0) + ' orders</div></div>' +
        '</div>';
    }).join('');
  } catch(e) { toast('Error: ' + e.message, true); }
}

// Revenue
async function loadRevenue() {
  try {
    var rev = await apiFetch('/admin/revenue');
    document.getElementById('revToday').textContent = '$' + (rev.today||0).toFixed(3);
    document.getElementById('revWeek').textContent  = '$' + (rev.week||0).toFixed(3);
    document.getElementById('revMonth').textContent = '$' + (rev.month||0).toFixed(3);
    document.getElementById('revAll').textContent   = '$' + (rev.allTime||0).toFixed(3);
    drawBarChart('revChart2', rev.daily || []);
  } catch(e) { toast('Error: ' + e.message, true); }
}

// User Modal
async function openUserModal(userId) {
  if (!userId) return;
  document.getElementById('userModal').classList.add('open');
  document.getElementById('modalUserTitle').textContent = 'Loading...';
  document.getElementById('modalUserBody').innerHTML = '<div class="loading-msg"><span class="spinner"></span>Loading...</div>';
  try {
    var data = await apiFetch('/admin/user/' + userId);
    var u = data.user, stats = data.stats || {};
    document.getElementById('modalUserTitle').textContent = u.username;
    var orders = (data.orders||[]);
    var ordersHtml = orders.length === 0
      ? '<div style="color:var(--text-muted);font-size:12px;padding:8px 0">No orders yet</div>'
      : orders.map(function(o) {
          return '<div class="mini-order-row">' +
            '<span class="mini-service">' + serviceIcon(o.service) + ' ' + (o.service||'--') + '</span>' +
            statusPill(o.status) +
            '<span class="mini-amount">' + fmtMoney(o.total) + '</span>' +
            '<span class="mini-date">' + timeAgo(o.createdAt) + '</span>' +
            '</div>';
        }).join('');

    document.getElementById('modalUserBody').innerHTML =
      '<div class="field-row">' +
        '<div class="field-group"><span class="field-label">Username</span><div class="field-val">' + u.username + '</div></div>' +
        '<div class="field-group"><span class="field-label">Role</span><div class="field-val">' + statusPill(u.role==='admin'?'processing':'pending').replace(/>.*</,'>'+( u.role||'user')+'<') + '</div></div>' +
      '</div>' +
      '<div class="field-group"><span class="field-label">Email</span><div class="field-val">' + (u.email||'--') + '</div></div>' +
      '<div class="field-row">' +
        '<div class="field-group"><span class="field-label">Balance</span><div class="field-val" style="color:var(--green);font-weight:700">' + fmtMoney(u.balance) + '</div></div>' +
        '<div class="field-group"><span class="field-label">Orders Done</span><div class="field-val">' + (stats.orderCount||0) + ' &bull; ' + fmtMoney(stats.totalSpent||0) + '</div></div>' +
      '</div>' +
      '<div class="field-group"><span class="field-label">Joined</span><div class="field-val">' + fmtDate(u.createdAt) + '</div></div>' +
      '<hr class="modal-divider">' +
      '<div class="modal-section-title">Top Up / Deduct Balance</div>' +
      '<input type="number" id="topupAmt" class="action-input" placeholder="Amount e.g. 1.000" min="0.01" step="0.01">' +
      '<input type="text" id="topupNote" class="action-input" placeholder="Note (optional)" style="margin-top:6px">' +
      '<button class="action-btn green" onclick="doTopup(\'' + u.id + '\')">+ Top Up</button>' +
      '<button class="action-btn red" style="margin-top:5px" onclick="doDeduct(\'' + u.id + '\')">- Deduct Balance</button>' +
      '<hr class="modal-divider">' +
      '<div class="modal-section-title">Change Role</div>' +
      '<select id="roleSelect" class="action-input"><option value="user"' + (u.role!=='admin'?' selected':'') + '>user</option><option value="admin"' + (u.role==='admin'?' selected':'') + '>admin</option></select>' +
      '<button class="action-btn amber" onclick="doSetRole(\'' + u.id + '\')">Change Role</button>' +
      '<hr class="modal-divider">' +
      '<div class="modal-section-title">Recent Orders (last 30)</div>' +
      ordersHtml;
  } catch(e) {
    document.getElementById('modalUserBody').innerHTML = '<div style="color:var(--red);padding:20px">' + e.message + '</div>';
  }
}

function closeModal() { document.getElementById('userModal').classList.remove('open'); }
document.getElementById('userModal').addEventListener('click', function(e){ if(e.target===this) closeModal(); });

async function doTopup(userId) {
  var amt = parseFloat(document.getElementById('topupAmt').value);
  var note = document.getElementById('topupNote').value || '';
  if (!amt || amt <= 0) { toast('Enter valid amount', true); return; }
  try {
    var r = await apiFetch('/admin/topup', { method:'POST', body: JSON.stringify({ userId:userId, amount:amt, note:note }) });
    toast(r.message || 'Done!');
    openUserModal(userId);
    if (allUsers.length) loadUsers();
  } catch(e) { toast('Error: ' + e.message, true); }
}

async function doDeduct(userId) {
  var amt = parseFloat(document.getElementById('topupAmt').value);
  var note = document.getElementById('topupNote').value || '';
  if (!amt || amt <= 0) { toast('Enter valid amount', true); return; }
  try {
    var r = await apiFetch('/admin/deduct', { method:'POST', body: JSON.stringify({ userId:userId, amount:amt, note:note }) });
    toast(r.message || 'Done!');
    openUserModal(userId);
  } catch(e) { toast('Error: ' + e.message, true); }
}

async function doSetRole(userId) {
  var role = document.getElementById('roleSelect').value;
  try {
    var r = await apiFetch('/admin/set-role', { method:'POST', body: JSON.stringify({ userId:userId, role:role }) });
    toast(r.message || 'Done!');
    openUserModal(userId);
  } catch(e) { toast('Error: ' + e.message, true); }
}

// Initial load
loadDashboard();
