const socket = io({
  auth: {
    token: localStorage.getItem('token')
  }
});

window.adminSocket = socket;

socket.on('user_online', userId => {
  window.dispatchEvent(
    new CustomEvent('user-online', { detail: userId })
  );
});

socket.on('user_offline', userId => {
  window.dispatchEvent(
    new CustomEvent('user-offline', { detail: userId })
  );
});


import { loadSidebar } from './components/sidebar.js';

// DOM references
const sidebar = document.getElementById('app-sidebar');
const content = document.getElementById('app-content');

/* ----------------------------------
   LOAD ADMIN CONTEXT
----------------------------------- */

async function loadAdminContext() {

  const token = localStorage.getItem('token');
  if (!token) return;

  try {

    const res = await fetch('/admin/api/profile', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    const data = await res.json();

    if (!data.success) {
      console.error('Failed to load admin profile');
      return;
    }

    const profile = data.profile;

    // Global admin context for dashboard
    window.currentUserRole = profile.role;
    window.currentUserName = `${profile.firstName} ${profile.lastName}`;
    window.currentUserEmail = profile.email;
    window.currentOrgName = profile.organizationName;

    console.log('ADMIN CONTEXT LOADED:', profile);

  } catch (err) {
    console.error('Admin context error:', err);
  }
}


/* ----------------------------------
   PANEL LOADER (GLOBAL)
----------------------------------- */

window.loadPanel = async function (panelName) {

  try {

    const module = await import(`./panels/${panelName}.js`);
    module.render(content);

  } catch (err) {

    console.error('Failed to load panel:', panelName, err);
    content.innerHTML = `<p>Panel not found</p>`;

  }
};


/* ----------------------------------
   DASHBOARD BOOTSTRAP
----------------------------------- */

(async function initDashboard() {

  // Load admin identity FIRST
  await loadAdminContext();

  // Render sidebar
  loadSidebar(sidebar);

  // Load default panel
  loadPanel('overview');

})();
