import { auth } from '../services/auth.js';
import { doliLogo, icons } from '../services/icons.js';

export function createSidebar(pages, currentPage) {
  const sidebar = document.createElement('aside');
  sidebar.className = 'sidebar';
  sidebar.id = 'sidebar';

  const sidebarHeader = document.createElement('div');
  sidebarHeader.className = 'sidebar-header';
  sidebarHeader.innerHTML = /*html*/`
    <div class="sidebar-brand">
      <div class="sidebar-logo-icon">
        ${doliLogo(26)}
      </div>
      <h2>Doli</h2>
    </div>
    <button class="sidebar-toggle" id="sidebar-toggle" aria-label="Alternar barra lateral">
      ${icons.menu}
    </button>
  `;

  const nav = document.createElement('nav');
  nav.className = 'sidebar-nav';

  const navList = document.createElement('ul');
  navList.className = 'sidebar-menu';

  pages.forEach(page => {
    const listItem = document.createElement('li');
    const link = document.createElement('a');
    link.href = `#${page.route}`;
    link.className = 'sidebar-link';
    if (page.route === currentPage) {
      link.classList.add('active');
    }
    link.innerHTML = /*html*/`
      <span class="sidebar-icon">${page.icon}</span>
      <span class="sidebar-text">${page.name}</span>
    `;
    listItem.appendChild(link);
    navList.appendChild(listItem);
  });

  nav.appendChild(navList);
  sidebar.appendChild(sidebarHeader);
  sidebar.appendChild(nav);

  const user = auth.getUser();
  const identifier = user?.identifier || user?.name || user?.login || '?';
  const initials = identifier.slice(0, 2).toUpperCase();

  const sidebarFooter = document.createElement('div');
  sidebarFooter.className = 'sidebar-footer';
  sidebarFooter.innerHTML = /*html*/`
    <div class="sidebar-user">
      <div class="sidebar-avatar">${initials}</div>
      <span class="sidebar-username">${identifier}</span>
    </div>
    <button class="sidebar-logout-btn" title="Cerrar sesión">
      ${icons.logout}
    </button>
  `;

  sidebarFooter.querySelector('.sidebar-logout-btn').addEventListener('click', () => {
    auth.logout();
    window.location.hash = '#login';
  });

  sidebar.appendChild(sidebarFooter);

  const toggleBtn = sidebarHeader.querySelector('#sidebar-toggle');
  toggleBtn.addEventListener('click', () => {
    if (window.matchMedia('(max-width: 768px)').matches) {
      document.dispatchEvent(new CustomEvent('sidebar:close-mobile'));
    } else {
      sidebar.classList.toggle('collapsed');
    }
  });

  return sidebar;
}