const TOKEN = localStorage.getItem('canifa_token');
const USER = JSON.parse(localStorage.getItem('canifa_user') || '{}');

// ═══ AUTH GUARD ═══
if (!TOKEN) { window.location.replace('login.html'); }
if (USER.role !== 'admin') {
  alert('Bạn không có quyền truy cập trang Admin');
  window.location.replace('main.html');
}

// Show user info
document.getElementById('topUsername').textContent = USER.username || 'admin';
document.getElementById('topAvatar').textContent = (USER.username || 'A').charAt(0).toUpperCase();

function logout() {
  localStorage.removeItem('canifa_token');
  localStorage.removeItem('canifa_user');
  window.location.replace('login.html');
}

// ═══ API HELPERS ═══
async function api(path, opts = {}) {
  const res = await fetch('/api/auth' + path, {
    headers: { 'Authorization': 'Bearer ' + TOKEN, 'Content-Type': 'application/json', ...opts.headers },
    ...opts,
  });
  if (res.status === 401) { logout(); return; }
  const data = await res.json();
  if (!res.ok) throw new Error(data.detail || 'Error');
  return data;
}

// ═══ PANELS ═══
function switchPanel(name, el) {
  document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
  document.getElementById('panel-' + name).classList.add('active');
  el.classList.add('active');
}

// ═══ LOAD STATS ═══
async function loadStats() {
  try {
    const data = await api('/stats');
    document.getElementById('statUsers').textContent = data.total_users;
    document.getElementById('statChats').textContent = data.chat_total.toLocaleString();
    document.getElementById('statToday').textContent = data.chat_today.toLocaleString();
    document.getElementById('roleAdmin').textContent = data.role_counts.admin || 0;
    document.getElementById('roleEditor').textContent = data.role_counts.editor || 0;
    document.getElementById('roleViewer').textContent = data.role_counts.viewer || 0;
  } catch (e) { console.error('Stats error:', e); }
}

// ═══ LOAD USERS ═══
async function loadUsers() {
  try {
    const data = await api('/users');
    const tbody = document.getElementById('usersBody');
    document.getElementById('userCount').textContent = data.users.length;
    tbody.innerHTML = data.users.map(u => `
      <tr>
        <td>#${u.id}</td>
        <td style="font-weight:600">${u.username}</td>
        <td><span class="role-badge ${u.role}">${u.role}</span></td>
        <td style="color:var(--text2);font-size:12px">${u.created_at ? new Date(u.created_at).toLocaleDateString('vi') : '—'}</td>
        <td style="color:var(--text2);font-size:12px">${u.last_login ? new Date(u.last_login).toLocaleString('vi') : 'Chưa đăng nhập'}</td>
        <td>
          <button class="btn-action" onclick="showEditModal(${u.id},'${u.username}','${u.role}')">Sửa</button>
          ${u.id !== USER.id ? `<button class="btn-action danger" onclick="deleteUser(${u.id},'${u.username}')">Xóa</button>` : ''}
        </td>
      </tr>
    `).join('');
  } catch (e) { console.error('Users error:', e); }
}

// ═══ MODAL ═══
function showCreateModal() {
  document.getElementById('modalTitle').textContent = 'Tạo User Mới';
  document.getElementById('editUserId').value = '';
  document.getElementById('modalUsername').value = '';
  document.getElementById('modalUsername').disabled = false;
  document.getElementById('modalPassword').value = '';
  document.getElementById('modalRole').value = 'viewer';
  document.getElementById('userModal').classList.add('show');
}

function showEditModal(id, username, role) {
  document.getElementById('modalTitle').textContent = 'Sửa User: ' + username;
  document.getElementById('editUserId').value = id;
  document.getElementById('modalUsername').value = username;
  document.getElementById('modalUsername').disabled = true;
  document.getElementById('modalPassword').value = '';
  document.getElementById('modalRole').value = role;
  document.getElementById('userModal').classList.add('show');
}

function closeModal() {
  document.getElementById('userModal').classList.remove('show');
}

async function submitUser() {
  const editId = document.getElementById('editUserId').value;
  const username = document.getElementById('modalUsername').value.trim();
  const password = document.getElementById('modalPassword').value;
  const role = document.getElementById('modalRole').value;

  try {
    if (editId) {
      // Update
      const body = { role };
      if (password) body.password = password;
      await api('/users/' + editId, { method: 'PUT', body: JSON.stringify(body) });
    } else {
      // Create
      if (!username || !password) { alert('Vui lòng nhập đầy đủ'); return; }
      await api('/users', { method: 'POST', body: JSON.stringify({ username, password, role }) });
    }
    closeModal();
    loadUsers();
    loadStats();
  } catch (e) { alert(e.message); }
}

async function deleteUser(id, username) {
  if (!confirm(`Xác nhận xóa user "${username}"?`)) return;
  try {
    await api('/users/' + id, { method: 'DELETE' });
    loadUsers();
    loadStats();
  } catch (e) { alert(e.message); }
}

// ═══ INIT ═══
loadStats();
loadUsers();