let paymentData = {};
let selectedAmount = 0;
let selectedMethod = '';

document.addEventListener('DOMContentLoaded', async () => {
  const token = localStorage.getItem('token');
  if (!token) { window.location.href = '/login.html'; return; }
  await refreshUserBalance();
  await loadPaymentInfo();
  await loadChargeHistory();
  initChargeForm();
  updateBalanceDisplay();
  loadStats();
});

async function loadStats() {
  const token = localStorage.getItem('token');
  try {
    const res = await fetch('/api/user/profile', { headers: { 'Authorization': 'Bearer ' + token } });
    const user = await res.json();
    
    document.getElementById('current-balance').textContent = formatMoney(user.balance || 0);
    document.getElementById('box-deposit').textContent = formatMoney(user.deposit_balance || 0);
    document.getElementById('box-pending').textContent = formatMoney(user.pending_balance || 0);
    document.getElementById('box-withdrawing').textContent = formatMoney(user.withdrawing_balance || 0);
    document.getElementById('box-withdrawn').textContent = formatMoney(user.withdrawn_balance || 0);
  } catch {}
}

function showAlert(message, type = 'success') {
  const container = document.getElementById('nh-toast-container');
  const toast = document.createElement('div');
  toast.className = `toast toast-${type}`;
  toast.style.cssText = `
      pointer-events: auto;
      min-width: 280px;
      max-width: 350px;
      background: ${type === 'success' ? 'rgba(16, 185, 129, 0.9)' : 'rgba(239, 68, 68, 0.9)'};
      backdrop-filter: blur(12px);
      border: 1px solid rgba(255, 255, 255, 0.1);
      color: white;
      padding: 16px 20px;
      border-radius: 14px;
      box-shadow: 0 10px 25px rgba(0,0,0,0.2);
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 14px;
      font-weight: 600;
      animation: toastSlideIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
      opacity: 0;
  `;
  
  const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
  toast.innerHTML = `
      <i class="fas ${icon}" style="font-size: 18px;"></i>
      <div style="flex: 1;">${message}</div>
      <i class="fas fa-times" style="cursor: pointer; opacity: 0.6; font-size: 12px;" onclick="this.parentElement.remove()"></i>
  `;
  
  container.appendChild(toast);
  
  setTimeout(() => {
      toast.style.animation = 'toastFadeOut 0.5s ease forwards';
      setTimeout(() => toast.remove(), 500);
  }, 4000);
}

function copyChargeContent() {
  const text = document.getElementById('charge-content').textContent;
  navigator.clipboard.writeText(text);
  const btn = document.getElementById('copy-content-btn');
  const originalText = btn.innerHTML;
  btn.innerHTML = '<i class="fas fa-check"></i> Đã Copy';
  btn.classList.add('copied');
  showAlert('Đã sao chép nội dung chuyển khoản');
  setTimeout(() => {
    btn.innerHTML = originalText;
    btn.classList.remove('copied');
  }, 2000);
}

async function loadPaymentInfo() {
  try {
    const res = await fetch('/api/charge/qr');
    paymentData = await res.json();
    renderMethods();
  } catch {}
}

function renderMethods() {
  const el = document.getElementById('charge-methods');
  if (!paymentData.methods) return;
  el.innerHTML = paymentData.methods.map((m, i) => `
    <button class="charge-method ${i === 0 ? 'active' : ''}" data-method="${m.id}" onclick="selectMethod('${m.id}', this)">${m.name}</button>
  `).join('');
  if (paymentData.methods.length) selectedMethod = paymentData.methods[0].id;
}

function selectMethod(id, btn) {
  document.querySelectorAll('.charge-method').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  selectedMethod = id;
  if (selectedAmount > 0) showQR();
}

function initChargeForm() {
  document.querySelectorAll('.amount-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.amount-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      selectedAmount = parseInt(btn.dataset.amount);
      document.getElementById('custom-amount').value = '';
      showQR();
      updateChargeBtn();
    });
  });

  document.getElementById('custom-amount').addEventListener('input', (e) => {
    const val = parseInt(e.target.value);
    if (val >= 10000) {
      document.querySelectorAll('.amount-btn').forEach(b => b.classList.remove('active'));
      selectedAmount = val;
      showQR();
    }
    updateChargeBtn();
  });

  document.getElementById('transaction-code').addEventListener('input', updateChargeBtn);

  document.getElementById('charge-btn').addEventListener('click', submitCharge);
}

function showQR() {
  const section = document.getElementById('qr-section');
  if (!selectedAmount || !selectedMethod) return;
  section.style.display = 'block';
  
  const content = paymentData.content + ' ' + selectedAmount;
  
  // Fetch dynamic QR if SePay is enabled
  fetch(`/api/charge/qr?amount=${selectedAmount}&content=${encodeURIComponent(content)}`)
    .then(res => res.json())
    .then(data => {
      const method = data.methods?.find(m => m.id === selectedMethod);
      document.getElementById('qr-image').src = data.dynamicQr || method?.qrImage || data.qrImage;
      document.getElementById('bank-name').textContent = data.bankName;
      document.getElementById('account-number').textContent = data.accountNumber;
      document.getElementById('account-name').textContent = data.accountName;
      document.getElementById('charge-content').textContent = content;
    });
}

function updateChargeBtn() {
  const code = document.getElementById('transaction-code').value.trim();
  const btn = document.getElementById('charge-btn');
  btn.disabled = !(selectedAmount >= 10000 && code.length > 0);
}

async function checkSePay(chargeId, btn) {
  const token = localStorage.getItem('token');
  const originalText = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Đang kiểm tra...';
  
  try {
    const res = await fetch('/api/charge/sepay-check', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
      body: JSON.stringify({ chargeId })
    });
    const data = await res.json();
    if (data.matched) {
      showAlert('Nạp tiền thành công!', 'success');
      setTimeout(() => window.location.reload(), 1500);
    } else {
      showAlert(data.message || 'Chưa tìm thấy giao dịch.', 'danger');
    }
  } catch (e) {
    showAlert('Lỗi khi kiểm tra giao dịch', 'danger');
  } finally {
    btn.disabled = false;
    btn.innerHTML = originalText;
  }
}

async function submitCharge() {
  const token = localStorage.getItem('token');
  if (!token) return;
  const code = document.getElementById('transaction-code').value.trim();
  const errorEl = document.getElementById('charge-error');
  const successEl = document.getElementById('charge-success');
  errorEl.style.display = 'none'; successEl.style.display = 'none';

  try {
    const res = await fetch('/api/charge/request', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
      body: JSON.stringify({ amount: selectedAmount, method: selectedMethod, transactionCode: code })
    });
    const data = await res.json();
    if (!res.ok) { 
      showAlert(data.error, 'danger');
      return; 
    }
    showAlert('Gửi yêu cầu nạp tiền thành công! Vui lòng chờ hệ thống xác nhận.');
    document.getElementById('transaction-code').value = '';
    loadChargeHistory();
  } catch { 
    showAlert('Lỗi kết nối', 'danger');
  }
}

async function loadChargeHistory() {
  const token = localStorage.getItem('token');
  try {
    const res = await fetch('/api/user/charges', { headers: { 'Authorization': 'Bearer ' + token } });
    const charges = await res.json();
    const el = document.getElementById('charge-history-list');
    if (!charges.length) { el.innerHTML = '<div class="nh-deposit-panel"><div class="empty-state"><i class="fas fa-receipt"></i><p>Chưa có lịch sử nạp tiền.</p></div></div>'; return; }
    
    el.innerHTML = `
      <div class="nh-history-panel">
        <table class="nh-history-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Nội dung / Mã GD</th>
                    <th>Số tiền</th>
                    <th>Trạng thái</th>
                </tr>
            </thead>
            <tbody>
                ${charges.reverse().map(c => `
                <tr>
                    <td style="color:var(--nh-muted);">#${c.id.split('-')[1] || c.id}<br><small>${new Date(c.createdAt).toLocaleString('vi-VN', {day:'2-digit', month:'2-digit', hour:'2-digit', minute:'2-digit'})}</small></td>
                    <td style="font-size:12px;color:var(--nh-sub);">
                      ${c.transactionCode}
                      ${c.sepay_transaction_id ? `<br><small style="color:var(--nh-green)">SePay: ${c.sepay_transaction_id}</small>` : ''}
                    </td>
                    <td style="color:var(--nh-orange);font-weight:600;">+${formatMoney(c.amount)}</td>
                    <td>
                        <div class="history-status-container">
                          <span class="nh-status-badge nh-status-${c.status === 'confirmed' ? 'completed' : c.status === 'pending' ? 'pending' : 'rejected'}">
                            ${c.status === 'pending' ? '⏳ Chờ' : c.status === 'confirmed' ? '✅ Xong' : '❌ Hủy'}
                          </span>
                          ${c.status === 'pending' ? `<button class="nh-copy-btn" style="padding:4px 8px; font-size:10px;" onclick="checkSePay('${c.id}', this)">Kiểm tra</button>` : ''}
                        </div>
                    </td>
                </tr>
                `).join('')}
            </tbody>
        </table>
      </div>
    `;
  } catch {}
}

function updateBalanceDisplay() {
  const user = JSON.parse(localStorage.getItem('user') || 'null');
  if (user) {
    const el = document.getElementById('current-balance');
    if (el) el.textContent = formatMoney(user.balance || 0);
  }
}
