let adminToken = localStorage.getItem('adminToken') || '';
let adminMasterKey = localStorage.getItem('adminMasterKey') || '';
let allGames = [];
let allAccounts = [];

const CATEGORIES = {
  moba: { id: 'moba', name: 'MOBA - Chiến thuật', icon: '⚔️' },
  fps: { id: 'fps', name: 'FPS - Bắn súng', icon: '🔫' },
  khac: { id: 'khac', name: 'Game khác', icon: '🎮' }
};

function api(url, opts = {}) {
  return fetch(url, {
    ...opts,
    headers: { 
      'Content-Type': 'application/json', 
      'Authorization': 'Bearer ' + adminToken,
      'x-admin-key': adminMasterKey, // Gửi key này lên server
      ...opts.headers 
    }
  }).then(async r => { const d = await r.json(); if (!r.ok) throw new Error(d.error); return d; });
}

function formatMoney(n) { return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(n); }

function showPage(page) {
  document.querySelectorAll('.page-section').forEach(s => s.classList.remove('active'));
  document.getElementById('page-' + page).classList.add('active');
  document.querySelectorAll('.sidebar-link').forEach(l => l.classList.remove('active'));
  event.target.closest('.sidebar-link').classList.add('active');
  if (page === 'dashboard') loadDashboard();
  if (page === 'games') loadGames();
  if (page === 'accounts') loadAccounts();
  if (page === 'charges') loadCharges();
  if (page === 'orders') loadOrders();
  if (page === 'users') loadUsers();
  if (page === 'payments') loadPayments();
}

function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }

async function adminLogin() {
  // Hàm này giờ có thể không dùng nữa vì đã có login.html riêng, 
  // nhưng ta giữ lại nếu cần login nhanh từ chỗ khác.
  window.location.href = '/admin/login.html';
}

function adminLogout() { 
  localStorage.removeItem('adminToken'); 
  localStorage.removeItem('adminMasterKey');
  // Xóa cookie adminToken
  document.cookie = "adminToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  document.cookie = "adminMasterKey=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  location.href = '/admin/login.html'; 
}

function checkAdmin() {
  const hasMasterKeyCookie = document.cookie.includes('adminMasterKey');
  if (!adminMasterKey && !hasMasterKeyCookie && !adminToken) {
    location.href = '/admin/login.html';
    return;
  }
  loadDashboard();
}

document.addEventListener('DOMContentLoaded', checkAdmin);

async function loadDashboard() {
  try {
    const d = await api('/api/admin/dashboard');
    document.getElementById('dashboard-stats').innerHTML = `
      <div class="stat-card"><div class="stat-card-icon revenue"><i class="fas fa-dollar-sign"></i></div><div class="stat-card-value">${formatMoney(d.totalRevenue)}</div><div class="stat-card-label">Doanh thu</div></div>
      <div class="stat-card"><div class="stat-card-icon orders"><i class="fas fa-shopping-cart"></i></div><div class="stat-card-value">${d.totalOrders}</div><div class="stat-card-label">Đơn hàng</div></div>
      <div class="stat-card"><div class="stat-card-icon users"><i class="fas fa-users"></i></div><div class="stat-card-value">${d.totalUsers}</div><div class="stat-card-label">Người dùng</div></div>
      <div class="stat-card"><div class="stat-card-icon accounts"><i class="fas fa-gamepad"></i></div><div class="stat-card-value">${d.totalAccounts}</div><div class="stat-card-label">Tài khoản game</div></div>
    `;
    const tbody = document.querySelector('#recent-orders-table tbody');
    tbody.innerHTML = (d.recentOrders || []).map(o => `<tr><td>${o.id}</td><td>${o.username}</td><td>${o.accountTitle}</td><td>${formatMoney(o.price)}</td><td>${new Date(o.createdAt).toLocaleString('vi-VN')}</td></tr>`).join('') || '<tr><td colspan="5" style="text-align:center;color:var(--text-muted)">Chưa có đơn hàng</td></tr>';
  } catch {}
}

async function loadGames() {
  try {
    allGames = await api('/api/admin/games');
    const tbody = document.querySelector('#games-table tbody');
    tbody.innerHTML = allGames.map(g => {
      const cat = CATEGORIES[g.category];
      return `<tr><td>${g.id}</td><td>${g.name}</td><td>${g.icon}</td><td>${cat ? cat.name : g.category}</td><td>${g.order}</td><td><span class="badge ${g.active ? 'badge-success' : 'badge-danger'}">${g.active ? 'Hiện' : 'Ẩn'}</span></td><td class="actions-cell"><button class="btn btn-outline btn-sm" onclick="editGame('${g.id}')"><i class="fas fa-edit"></i></button><button class="btn btn-danger btn-sm" onclick="deleteGame('${g.id}')"><i class="fas fa-trash"></i></button></td></tr>`;
    }).join('');
  } catch {}
}

async function uploadImage(file) {
  const formData = new FormData();
  formData.append('image', file);
  try {
    const res = await fetch('/api/admin/upload', {
      method: 'POST',
      headers: { 'Authorization': 'Bearer ' + adminToken },
      body: formData
    });
    const data = await res.json();
    if (data.success) return data.path;
    throw new Error(data.error || 'Upload failed');
  } catch (e) { alert('Lỗi upload ảnh: ' + e.message); return ''; }
}

function showGameModal(game) {
  document.getElementById('modal-title').textContent = game ? 'Sửa Game' : 'Thêm Game';
  const catOpts = Object.values(CATEGORIES).map(c => `<option value="${c.id}" ${game?.category === c.id ? 'selected' : ''}>${c.icon} ${c.name}</option>`).join('');
  document.getElementById('modal-body').innerHTML = `
    <div class="form-group"><label>Tên game</label><input type="text" id="mg-name" value="${game?.name || ''}"></div>
    <div class="form-group"><label>Slug</label><input type="text" id="mg-slug" value="${game?.slug || ''}"></div>
    <div class="form-group"><label>Icon (emoji)</label><input type="text" id="mg-icon" value="${game?.icon || '🎮'}"></div>
    <div class="form-group"><label>Danh mục</label><select id="mg-category"><option value="khac">🎮 Game khác</option>${catOpts}</select></div>
    <div class="form-group"><label>Ảnh bìa (URL hoặc upload)</label><input type="text" id="mg-image" value="${game?.image || ''}" placeholder="/img/game.jpg hoặc URL">
    <input type="file" id="mg-image-upload" accept="image/*" style="margin-top:8px" onchange="handleGameImageUpload()"></div>
    <div class="form-group"><label>Ảnh cover (URL hoặc upload)</label><input type="text" id="mg-coverImage" value="${game?.coverImage || ''}" placeholder="/uploads/cover.jpg hoặc URL">
    <input type="file" id="mg-cover-upload" accept="image/*" style="margin-top:8px" onchange="handleGameCoverUpload()"></div>
    <div class="form-group"><label>Gradient (nếu không có ảnh)</label><input type="text" id="mg-coverGradient" value="${game?.coverGradient || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'}"></div>
    <div class="form-group"><label>Thứ tự</label><input type="number" id="mg-order" value="${game?.order || allGames.length + 1}"></div>
    <button class="btn btn-primary" onclick="saveGame('${game?.id || ''}')">Lưu</button>
  `;
  document.getElementById('modal-overlay').classList.add('active');
}

async function handleGameImageUpload() {
  const file = document.getElementById('mg-image-upload').files[0];
  if (file) {
    const path = await uploadImage(file);
    if (path) document.getElementById('mg-image').value = path;
  }
}

async function handleGameCoverUpload() {
  const file = document.getElementById('mg-cover-upload').files[0];
  if (file) {
    const path = await uploadImage(file);
    if (path) document.getElementById('mg-coverImage').value = path;
  }
}

async function saveGame(id) {
  const data = {
    name: document.getElementById('mg-name').value,
    slug: document.getElementById('mg-slug').value,
    icon: document.getElementById('mg-icon').value,
    category: document.getElementById('mg-category').value,
    image: document.getElementById('mg-image').value,
    coverImage: document.getElementById('mg-coverImage').value,
    coverGradient: document.getElementById('mg-coverGradient').value,
    order: document.getElementById('mg-order').value
  };
  try {
    if (id) await api('/api/admin/games/' + id, { method: 'PUT', body: JSON.stringify(data) });
    else await api('/api/admin/games', { method: 'POST', body: JSON.stringify(data) });
    closeModal(); loadGames();
  } catch (e) { alert(e.message); }
}

function editGame(id) { const g = allGames.find(x => x.id === id); if (g) showGameModal(g); }

async function deleteGame(id) { if (!confirm('Xóa game này?')) return; try { await api('/api/admin/games/' + id, { method: 'DELETE' }); loadGames(); } catch (e) { alert(e.message); } }

let selectedGameId = null;

async function loadAccounts() {
  try {
    allAccounts = await api('/api/admin/accounts');
    if (!allGames.length) allGames = await api('/api/admin/games');
    
    if (selectedGameId) {
      showAccountsByGame(selectedGameId);
    } else {
      showAccountGameList();
    }
  } catch {}
}

function showAccountGameList() {
  selectedGameId = null;
  const gameListView = document.getElementById('accounts-game-list-view');
  const detailView = document.getElementById('accounts-detail-view');
  
  if (gameListView) gameListView.style.display = 'block';
  if (detailView) detailView.style.display = 'none';
  
  const grid = document.getElementById('admin-game-grid');
  if (!grid) return;
  
  grid.innerHTML = allGames.map(g => {
    const accCount = allAccounts.filter(a => a.gameId === g.id).length;
    const totalStock = allAccounts.filter(a => a.gameId === g.id).reduce((sum, a) => sum + a.stock, 0);
    
    return `
      <div class="admin-game-card" onclick="showAccountsByGame('${g.id}')">
        <div class="admin-game-icon">${g.icon || '🎮'}</div>
        <h3>${g.name}</h3>
        <div class="admin-game-stats">
          <span>${accCount} mục con</span> • <span>Kho: ${totalStock}</span>
        </div>
      </div>
    `;
  }).join('');
}

function showAccountsByGame(gameId) {
  selectedGameId = gameId;
  const game = allGames.find(g => g.id === gameId);
  if (!game) return showAccountGameList();

  const gameListView = document.getElementById('accounts-game-list-view');
  const detailView = document.getElementById('accounts-detail-view');
  
  if (gameListView) gameListView.style.display = 'none';
  if (detailView) detailView.style.display = 'block';
  
  const titleEl = document.getElementById('selected-game-title');
  if (titleEl) titleEl.textContent = game.name;

  const filteredAccounts = allAccounts.filter(a => a.gameId === gameId);
  const tbody = document.querySelector('#accounts-table tbody');
  if (!tbody) return;
  
  tbody.innerHTML = filteredAccounts.map(a => `
    <tr>
      <td style="max-width:100px;overflow:hidden;text-overflow:ellipsis">${a.id}</td>
      <td style="max-width:250px;overflow:hidden;text-overflow:ellipsis">${a.title}</td>
      <td><span class="badge badge-primary">${a.type}</span></td>
      <td>${formatMoney(a.price)}</td>
      <td>${a.stock}</td>
      <td>${a.sold}</td>
      <td class="actions-cell">
        <button class="btn btn-outline btn-sm" onclick="editAccount('${a.id}')"><i class="fas fa-edit"></i></button>
        <button class="btn btn-danger btn-sm" onclick="deleteAccount('${a.id}')"><i class="fas fa-trash"></i></button>
      </td>
    </tr>
  `).join('') || '<tr><td colspan="7" style="text-align:center;color:var(--text-muted)">Chưa có mục con nào trong game này</td></tr>';
}

function showAccountModal(acc) {
  document.getElementById('modal-title').textContent = acc ? 'Sửa Mục Game' : 'Thêm Mục Game';
  
  // If we are in a game view, pre-select that game
  const defaultGameId = selectedGameId || (allGames.length > 0 ? allGames[0].id : '');
  const gameOpts = allGames.map(g => `<option value="${g.id}" ${(acc?.gameId || defaultGameId) === g.id ? 'selected' : ''}>${g.name}</option>`).join('');
  
  document.getElementById('modal-body').innerHTML = `
    <div class="form-group"><label>Game (Sản phẩm tiêu biểu)</label><select id="ma-game">${gameOpts}</select></div>
    <div class="form-group"><label>Loại (vd: tự chọn, random 20k)</label><input type="text" id="ma-type" value="${acc?.type || 'tự chọn'}"></div>
    <div class="form-group"><label>Tiêu đề (Mục Game con)</label><input type="text" id="ma-title" value="${acc?.title || ''}"></div>
    <div class="form-group"><label>Mô tả</label><textarea id="ma-desc">${acc?.description || ''}</textarea></div>
    <div class="form-group"><label>Thông tin hiển thị (vd: Rank Kim Cương, 100 Skin...)</label><input type="text" id="ma-info" value="${acc?.info || ''}"></div>
    <div class="form-group"><label>Giá bán (VND)</label><input type="number" id="ma-price" value="${acc?.price || ''}"></div>
    
    <div class="form-group">
      <label>Danh sách tài khoản (Mỗi dòng 1 tài khoản)</label>
      <p style="font-size:12px;color:var(--text-muted);margin-bottom:8px">Định dạng gợi ý: user|pass hoặc chỉ pass. Tự động cập nhật số lượng theo dòng.</p>
      <textarea id="ma-accountList" placeholder="user1|pass1\nuser2|pass2" style="height:150px">${acc?.credentials ? acc.credentials.join('\n') : ''}</textarea>
    </div>

    <div class="form-group"><label>Ảnh thumbnail (URL hoặc upload)</label><input type="text" id="ma-image" value="${acc?.image || ''}" placeholder="/img/game.jpg hoặc URL">
    <input type="file" id="ma-image-upload" accept="image/*" style="margin-top:8px" onchange="handleAccImageUpload()"></div>
    <div class="form-group"><label>Ảnh bìa/cover (URL hoặc upload)</label><input type="text" id="ma-coverImage" value="${acc?.coverImage || ''}" placeholder="/uploads/cover.jpg hoặc URL">
    <input type="file" id="ma-cover-upload" accept="image/*" style="margin-top:8px" onchange="handleAccCoverUpload()"></div>
    <div class="form-group"><label>Trạng thái</label><select id="ma-active"><option value="true" ${acc?.active !== false ? 'selected' : ''}>Hiện</option><option value="false" ${acc?.active === false ? 'selected' : ''}>Ẩn</option></select></div>
    <button class="btn btn-primary" onclick="saveAccount('${acc?.id || ''}')">Lưu</button>
  `;
  document.getElementById('modal-overlay').classList.add('active');
}

async function handleAccImageUpload() {
  const file = document.getElementById('ma-image-upload').files[0];
  if (file) {
    const path = await uploadImage(file);
    if (path) document.getElementById('ma-image').value = path;
  }
}

async function handleAccCoverUpload() {
  const file = document.getElementById('ma-cover-upload').files[0];
  if (file) {
    const path = await uploadImage(file);
    if (path) document.getElementById('ma-coverImage').value = path;
  }
}

async function saveAccount(id) {
  const data = {
    gameId: document.getElementById('ma-game').value, 
    type: document.getElementById('ma-type').value,
    title: document.getElementById('ma-title').value, 
    description: document.getElementById('ma-desc').value,
    info: document.getElementById('ma-info').value, 
    price: document.getElementById('ma-price').value,
    accountList: document.getElementById('ma-accountList').value,
    image: document.getElementById('ma-image').value,
    coverImage: document.getElementById('ma-coverImage').value,
    active: document.getElementById('ma-active').value === 'true'
  };
  try {
    if (id) await api('/api/admin/accounts/' + id, { method: 'PUT', body: JSON.stringify(data) });
    else await api('/api/admin/accounts', { method: 'POST', body: JSON.stringify(data) });
    closeModal(); 
    loadAccounts(); // This will refresh the view
  } catch (e) { alert(e.message); }
}

function editAccount(id) { const a = allAccounts.find(x => x.id === id); if (a) showAccountModal(a); }
async function deleteAccount(id) { if (!confirm('Xóa mục này?')) return; try { await api('/api/admin/accounts/' + id, { method: 'DELETE' }); loadAccounts(); } catch (e) { alert(e.message); } }

async function loadCharges() {
  try {
    const charges = await api('/api/admin/charges');
    document.getElementById('pending-count').textContent = charges.filter(c => c.status === 'pending').length + ' chờ xác nhận';
    const tbody = document.querySelector('#charges-table tbody');
    tbody.innerHTML = charges.reverse().map(c => `<tr>
      <td style="max-width:100px;overflow:hidden;text-overflow:ellipsis">${c.id}</td>
      <td>${c.username}</td>
      <td>${formatMoney(c.amount)}</td>
      <td>${c.method}</td>
      <td>
        ${c.transactionCode}
        ${c.sepay_transaction_id ? `<br><small style="color:var(--success)">SePay: ${c.sepay_transaction_id}</small>` : ''}
      </td>
      <td><span class="badge badge-${c.status === 'confirmed' ? 'success' : c.status === 'pending' ? 'warning' : 'danger'}">${c.status === 'confirmed' ? 'Đã xác nhận' : c.status === 'pending' ? 'Chờ xác nhận' : 'Từ chối'}</span></td>
      <td>${new Date(c.createdAt).toLocaleString('vi-VN')}</td>
      <td class="actions-cell">${c.status === 'pending' ? `<button class="btn btn-success btn-sm" onclick="confirmCharge('${c.id}')"><i class="fas fa-check"></i></button><button class="btn btn-danger btn-sm" onclick="rejectCharge('${c.id}')"><i class="fas fa-times"></i></button>` : '-'}</td>
    </tr>`).join('');
  } catch {}
}

async function confirmCharge(id) { if (!confirm('Xác nhận nạp tiền?')) return; try { await api('/api/admin/charges/' + id + '/confirm', { method: 'POST' }); loadCharges(); } catch (e) { alert(e.message); } }
async function rejectCharge(id) { if (!confirm('Từ chối nạp tiền?')) return; try { await api('/api/admin/charges/' + id + '/reject', { method: 'POST' }); loadCharges(); } catch (e) { alert(e.message); } }

async function loadOrders() {
  try {
    const orders = await api('/api/admin/orders');
    const tbody = document.querySelector('#orders-table tbody');
    tbody.innerHTML = orders.reverse().map(o => `<tr><td style="max-width:100px;overflow:hidden;text-overflow:ellipsis">${o.id}</td><td>${o.username}</td><td style="max-width:200px;overflow:hidden;text-overflow:ellipsis">${o.accountTitle}</td><td>${formatMoney(o.price)}</td><td><span class="badge badge-success">Hoàn thành</span></td><td>${new Date(o.createdAt).toLocaleString('vi-VN')}</td></tr>`).join('') || '<tr><td colspan="6" style="text-align:center;color:var(--text-muted)">Chưa có đơn hàng</td></tr>';
  } catch {}
}

async function loadUsers() {
  try {
    const users = await api('/api/admin/users');
    const tbody = document.querySelector('#users-table tbody');
    tbody.innerHTML = users.map(u => `<tr><td style="max-width:100px;overflow:hidden;text-overflow:ellipsis">${u.id}</td><td>${u.username}</td><td>${u.email}</td><td>${formatMoney(u.balance)}</td><td><span class="badge ${u.active ? 'badge-success' : 'badge-danger'}">${u.active ? 'Hoạt động' : 'Bị khóa'}</span></td><td>${new Date(u.createdAt).toLocaleDateString('vi-VN')}</td><td>${u.role !== 'admin' ? `<button class="btn ${u.active ? 'btn-danger' : 'btn-success'} btn-sm" onclick="toggleUser('${u.id}')">${u.active ? 'Khóa' : 'Mở khóa'}</button>` : '-'}</td></tr>`).join('');
  } catch {}
}

async function toggleUser(id) { try { await api('/api/admin/users/' + id + '/toggle', { method: 'POST' }); loadUsers(); } catch (e) { alert(e.message); } }

async function loadPayments() {
  try {
    const data = await api('/api/charge/qr');
    document.getElementById('pay-bank-name').value = data.bankName || '';
    document.getElementById('pay-account-number').value = data.accountNumber || '';
    document.getElementById('pay-account-name').value = data.accountName || '';
    document.getElementById('pay-content').value = data.content || '';
    document.getElementById('pay-sepay-token').value = data.sepayApiToken || '';
    document.getElementById('pay-sepay-account-id').value = data.sepayAccountId || '';
    document.getElementById('pay-sepay-bank').value = data.sepayBankName || 'MBBank';
    renderPaymentMethods(data.methods || []);
  } catch {}
}

function renderPaymentMethods(methods) {
  const el = document.getElementById('payment-methods-list');
  el.innerHTML = methods.map((m, i) => `
    <div class="form-group" style="background:var(--bg-secondary);padding:12px;border-radius:8px;margin-bottom:8px">
      <div style="display:flex;gap:8px;align-items:center">
        <input type="text" class="pm-id" value="${m.id}" placeholder="ID (vd: momo)" style="flex:1">
        <input type="text" class="pm-name" value="${m.name}" placeholder="Tên phương thức" style="flex:2">
        <button class="btn btn-danger btn-sm" onclick="this.closest('.form-group').remove()"><i class="fas fa-trash"></i></button>
      </div>
      <input type="text" class="pm-qr" value="${m.qrImage || ''}" placeholder="QR Image URL" style="margin-top:8px;width:100%">
    </div>
  `).join('');
}

function addPaymentMethod() {
  const el = document.getElementById('payment-methods-list');
  el.innerHTML += `
    <div class="form-group" style="background:var(--bg-secondary);padding:12px;border-radius:8px;margin-bottom:8px">
      <div style="display:flex;gap:8px;align-items:center">
        <input type="text" class="pm-id" placeholder="ID (vd: momo)" style="flex:1">
        <input type="text" class="pm-name" placeholder="Tên phương thức" style="flex:2">
        <button class="btn btn-danger btn-sm" onclick="this.closest('.form-group').remove()"><i class="fas fa-trash"></i></button>
      </div>
      <input type="text" class="pm-qr" placeholder="QR Image URL" style="margin-top:8px;width:100%">
    </div>
  `;
}

async function savePaymentSettings() {
  const methods = [];
  document.querySelectorAll('#payment-methods-list .form-group').forEach(el => {
    methods.push({ id: el.querySelector('.pm-id').value, name: el.querySelector('.pm-name').value, qrImage: el.querySelector('.pm-qr').value });
  });
  const data = {
    bankName: document.getElementById('pay-bank-name').value,
    accountNumber: document.getElementById('pay-account-number').value,
    accountName: document.getElementById('pay-account-name').value,
    content: document.getElementById('pay-content').value,
    sepayApiToken: document.getElementById('pay-sepay-token').value,
    sepayAccountId: document.getElementById('pay-sepay-account-id').value,
    sepayBankName: document.getElementById('pay-sepay-bank').value,
    methods,
    qrImage: '/img/qr-sample.png'
  };
  try {
    await api('/api/admin/payments', { method: 'PUT', body: JSON.stringify(data) });
    const msg = document.getElementById('pay-save-msg');
    msg.textContent = 'Đã lưu thành công!'; msg.style.display = 'block';
    setTimeout(() => msg.style.display = 'none', 3000);
  } catch (e) { alert(e.message); }
}

function closeModal() { document.getElementById('modal-overlay').classList.remove('active'); }
document.getElementById('modal-overlay').addEventListener('click', (e) => { if (e.target === e.currentTarget) closeModal(); });