const sidebar = document.getElementById("sidebar");
const main = document.getElementById("main");

// Track toggle manually
let isSidebarOpen = true;

// Toggle sidebar normally
function toggleSidebar() {
  isSidebarOpen = !isSidebarOpen;

  sidebar.classList.toggle("hide", !isSidebarOpen);

  // Add temporary transition only during toggle
  main.style.transition = "margin-left 0.3s ease";
  sidebar.style.transition = "left 0.3s ease";

  // Adjust main margin
  main.style.marginLeft = isSidebarOpen ? "260px" : "20px";

  // Remove transitions after animation to avoid disturbance
  setTimeout(() => {
    main.style.transition = "none";
    sidebar.style.transition = "none";
  }, 300);
}

// Toggle submenu — also force sidebar to open if it is hidden
function toggleMenu(id) {
  const menu = document.getElementById(id);
  if (!menu) return;

  // 👉 If sidebar is collapsed, open it automatically
  if (!isSidebarOpen) {
    isSidebarOpen = true;
    sidebar.classList.remove("hide");
    main.style.marginLeft = "260px";
  }

  // Close all other submenus
  document.querySelectorAll(".submenu").forEach(sm => {
    if (sm !== menu) sm.style.display = "none";
  });

  // Toggle the clicked submenu instantly
  menu.style.display = menu.style.display === "block" ? "none" : "block";
}

// Remove transition when clicking submenu links
document.querySelectorAll(".submenu a").forEach(link => {
  link.addEventListener("click", () => {
    main.style.transition = "none";
    sidebar.style.transition = "none";
  });
});

// Initialize sidebar as open when page loads
window.addEventListener("DOMContentLoaded", () => {
  sidebar.classList.remove("hide");
  main.style.marginLeft = "260px";
  isSidebarOpen = true;
});
