// =========================================================
// FILE: sidebar.js  — v2
// Builds the app sidebar and handles mobile toggle.
// =========================================================

const sidebarMount   = document.getElementById("sidebarMount");
const mobileToggle   = document.getElementById("mobileMenuToggle");
const sidebarOverlay = document.getElementById("sidebarOverlay");

const navSections = [
  {
    title: "Performance",
    items: [
      { label: "Dashboard",       icon: "fa-gauge-high",      href: "dashboard.html",            roles: "director,coach" },
      { label: "My Dashboard",    icon: "fa-gauge-high",      href: "player-dashboard.html",     roles: "player" },
      { label: "Bio Dashboard",   icon: "fa-stethoscope",     href: "bio-dashboard.html",        roles: "biokineticist" },
      { label: "Reports",         icon: "fa-chart-bar",       href: "reports.html",              roles: "director,coach,biokineticist" },
    ]
  },
  {
    title: "Operations",
    items: [
      { label: "Teams",           icon: "fa-layer-group",     href: "teams.html",                roles: "director" },
      { label: "Players",         icon: "fa-users",           href: "players.html",              roles: "director,coach,biokineticist" },
      { label: "Matches",         icon: "fa-trophy",          href: "matches.html",              roles: "director,coach" },
      { label: "Training",        icon: "fa-dumbbell",        href: "training.html",             roles: "director,coach" },
      { label: "Attendance",      icon: "fa-clipboard-check", href: "attendance.html",           roles: "director,coach" },
    ]
  },
  {
    title: "Medical",
    items: [
      { label: "Wellness",        icon: "fa-heart-pulse",     href: "wellness.html",             roles: "director,coach,player" },
      { label: "Wellness Review", icon: "fa-heart-pulse",     href: "bio-wellness.html",         roles: "biokineticist" },
      { label: "Injuries",        icon: "fa-kit-medical",     href: "injuries.html",             roles: "director,coach,biokineticist" },
    ]
  },
  {
    title: "System",
    items: [
      { label: "My Profile",       icon: "fa-circle-user",    href: "profile.html",              roles: "director,coach,biokineticist,player" },
      { label: "Notifications",    icon: "fa-bell",           href: "notifications.html",        roles: "director,coach,biokineticist,player", badge: true },
      { label: "User Management",  icon: "fa-users-gear",     href: "user-management.html",      roles: "director" },
      { label: "Organisation",     icon: "fa-building",       href: "organisation-settings.html",roles: "director" },
      { label: "Subscription",     icon: "fa-credit-card",    href: "subscription.html",         roles: "director" },
    ]
  }
];

function getCurrentPage() {
  const path = window.location.pathname;
  return path.substring(path.lastIndexOf("/") + 1) || "dashboard.html";
}

function buildSidebar() {
  if (!sidebarMount) return;

  const currentPage = getCurrentPage();

  const sectionsHtml = navSections.map(function (section) {
    const itemsHtml = section.items.map(function (item) {
      const isActive = item.href === currentPage;
      return [
        '<a href="' + item.href + '"',
        ' class="sidebar-link' + (isActive ? ' active' : '') + '"',
        ' data-role-access="' + item.roles + '"',
        ' aria-current="' + (isActive ? 'page' : 'false') + '">',
        '<span class="sidebar-icon" aria-hidden="true"><i class="fa-solid ' + item.icon + '"></i></span>',
        '<span class="sidebar-label">' + item.label + '</span>',
        item.badge ? '<strong id="notificationBadge" class="sidebar-notification-badge hidden" aria-label="unread notifications">0</strong>' : '',
        '</a>'
      ].join('');
    }).join('');

    return [
      '<div class="sidebar-section">',
      '<div class="sidebar-section-title" aria-hidden="true">' + section.title + '</div>',
      '<nav class="sidebar-nav" aria-label="' + section.title + '">' + itemsHtml + '</nav>',
      '</div>'
    ].join('');
  }).join('');

  sidebarMount.innerHTML = [
    '<aside class="sidebar elite-sidebar" aria-label="Main navigation">',
    '<div class="sidebar-top">',
    '<div class="sidebar-brand">',
    '<img src="assets/trytrack-logo.png" alt="TryTrack" class="sidebar-logo-image" width="160" loading="lazy" />',
    '</div></div>',
    '<div class="sidebar-scroll">' + sectionsHtml + '</div>',
    '<div class="sidebar-footer">',
    '<div class="sidebar-user-card">',
    '<div class="sidebar-user-avatar" id="userAvatar" aria-hidden="true">TT</div>',
    '<div class="sidebar-user-info"><strong id="userDisplay">Loading...</strong><small>Online</small></div>',
    '</div>',
    '<button id="logoutBtn" class="sidebar-logout-btn" type="button">',
    '<i class="fa-solid fa-arrow-right-from-bracket" aria-hidden="true"></i> Logout',
    '</button>',
    '</div></aside>'
  ].join('');
}

function getSidebar() {
  return document.querySelector('.elite-sidebar');
}

function closeSidebar() {
  const sidebar = getSidebar();
  if (!sidebar) return;
  sidebar.classList.remove('sidebar-open');
  if (sidebarOverlay) sidebarOverlay.classList.remove('active');
  document.body.classList.remove('menu-open');
  if (mobileToggle) mobileToggle.setAttribute('aria-expanded', 'false');
}

function setupMobileSidebar() {
  const sidebar = getSidebar();
  if (!mobileToggle || !sidebar) return;

  mobileToggle.addEventListener('click', function () {
    var isOpen = sidebar.classList.contains('sidebar-open');
    if (isOpen) {
      closeSidebar();
    } else {
      sidebar.classList.add('sidebar-open');
      if (sidebarOverlay) sidebarOverlay.classList.add('active');
      document.body.classList.add('menu-open');
      mobileToggle.setAttribute('aria-expanded', 'true');
    }
  });

  if (sidebarOverlay) {
    sidebarOverlay.addEventListener('click', closeSidebar);
  }

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') closeSidebar();
  });

  document.querySelectorAll('.sidebar-nav a').forEach(function (link) {
    link.addEventListener('click', function () {
      if (window.innerWidth <= 980) closeSidebar();
    });
  });
}

if (sidebarMount && !document.querySelector('.sidebar')) {
  buildSidebar();
}

setupMobileSidebar();

window.updateNotificationBadge = function (count) {
  var badge = document.getElementById('notificationBadge');
  if (!badge) return;
  if (!count || count <= 0) {
    badge.textContent = '0';
    badge.classList.add('hidden');
    return;
  }
  badge.textContent = count > 99 ? '99+' : String(count);
  badge.setAttribute('aria-label', count + ' unread notifications');
  badge.classList.remove('hidden');
};
