function getAuthHeaders() {
  const token = localStorage.getItem('token');
  return token ? { 'Authorization': 'Bearer ' + token } : {};
}

function updateAuthUI() {
  const token = localStorage.getItem('token');
  const user = JSON.parse(localStorage.getItem('user') || 'null');
  const authEl = document.getElementById('auth-buttons');
  const navProfile = document.getElementById('nav-profile');
  if (!authEl) return;
  if (token && user) {
    authEl.innerHTML = `
      <span class="user-info"><i class="fas fa-user"></i> ${user.username}</span>
      <span class="user-balance-text"><i class="fas fa-wallet"></i> ${formatMoney(user.balance)}</span>
      <a href="/profile.html"><i class="fas fa-user-circle"></i> Hồ sơ</a>
      <a href="#" onclick="logout()" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Thoát</a>
    `;
    if (navProfile) navProfile.style.display = '';
  } else {
    authEl.innerHTML = `
      <a href="/login.html" class="login-btn"><i class="fas fa-sign-in-alt"></i> Đăng nhập</a>
      <a href="/register.html" class="register-btn"><i class="fas fa-user-plus"></i> Đăng ký</a>
    `;
    if (navProfile) navProfile.style.display = 'none';
  }
}

function logout() {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  window.location.href = '/';
}

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

async function refreshUserBalance() {
  const token = localStorage.getItem('token');
  if (!token) return;
  try {
    const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
    if (res.ok) {
      const profile = await res.json();
      const user = JSON.parse(localStorage.getItem('user'));
      if (user) { user.balance = profile.balance; localStorage.setItem('user', JSON.stringify(user)); }
      updateAuthUI();
    }
  } catch {}
}

document.addEventListener('DOMContentLoaded', () => {
  updateAuthUI();
});
