import { auth } from './services/auth.js';
import { renderLoginPage } from './pages/LoginPage.js';
import { createSidebar } from './components/Sidebar.js';
import { getAvailablePages, getPageByRoute } from './pages/pagesRegistry.js';
import { showConfirmExitModal } from './components/ConfirmExitModal.js';
import { applyLoginTheme, applySavedTheme } from './services/theme.js';
import { hideVoiceAssistant, showVoiceAssistant } from './components/VoiceAssistant.js';

// 🔧 Modo DEV: cambiar a false para activar login
const DEV_MODE = false;

// Sistema de guards para bloquear navegación
const navigationGuards = {
  currentGuard: null,
  
  // Registrar un guard (función que devuelve true si hay cambios sin guardar)
  register(checkFn) {
    this.currentGuard = checkFn;
  },
  
  // Eliminar el guard actual
  unregister() {
    this.currentGuard = null;
  },
  
  // Verificar si hay cambios pendientes
  hasUnsavedChanges() {
    return this.currentGuard ? this.currentGuard() : false;
  }
};

// Exportar para uso en páginas
export { navigationGuards };

export function initRouter() {
  const app = document.querySelector('#app');
  let isNavigating = false;
  let pendingHash = null;
  let currentPageCleanup = null;

  async function navigate(forceNavigate = false) {
    const hash = window.location.hash || (DEV_MODE ? '#dashboard' : '#login');
    const route = hash.substring(1);

    // Auth check first — a forced logout must never be blocked by the unsaved-changes guard
    if (!DEV_MODE && !auth.checkAuth() && hash !== '#login') {
      navigationGuards.unregister();
      window.location.hash = '#login';
      return;
    }

    // Si hay un guard activo y no estamos forzando navegación
    if (!forceNavigate && navigationGuards.hasUnsavedChanges()) {
      // Guardar el hash al que se quiere ir
      pendingHash = hash;

      // Volver al hash anterior temporalmente
      const previousHash = '#' + (document.querySelector('.main-content')?.dataset?.currentRoute || 'dashboard');
      history.pushState(null, '', previousHash);

      // Mostrar modal de confirmación
      const confirmed = await showConfirmExitModal({
        title: 'Cambios sin guardar',
        message: 'Tienes cambios sin guardar. ¿Seguro que quieres salir?',
        confirmText: 'Salir sin guardar',
        cancelText: 'Seguir editando'
      });

      if (confirmed) {
        // Usuario confirmó salir - limpiar guard y navegar
        navigationGuards.unregister();
        window.location.hash = pendingHash;
      }
      // Si no confirmó, ya estamos en la página correcta
      pendingHash = null;
      return;
    }

    if (typeof currentPageCleanup === 'function') {
      currentPageCleanup();
      currentPageCleanup = null;
    }

    // Remove any body-level modals left open from the previous page
    document.querySelectorAll('body > [class*="overlay"], body > [class*="modal"]').forEach(el => {
      if (!el.classList.contains('connection-lost-overlay')) el.remove();
    });

    if (hash === '#login') {
      applyLoginTheme();
      hideVoiceAssistant();
    } else {
      applySavedTheme();
      showVoiceAssistant();
    }

    app.innerHTML = '';

    // For authenticated routes, add sidebar and main content wrapper
    const isAuthenticated = DEV_MODE || auth.checkAuth();
    if (isAuthenticated && hash !== '#login') {
      const layout = document.createElement('div');
      layout.className = 'app-layout';

      // Create sidebar
      const pages = getAvailablePages(true);
      const sidebar = createSidebar(pages, route);

      // Create main content area
      const mainContent = document.createElement('main');
      mainContent.className = 'main-content';
      mainContent.dataset.currentRoute = route; // Guardar ruta actual

      // Get page from registry
      const page = getPageByRoute(route);

      if (!page) {
        // For unregistered routes, redirect to dashboard
        window.location.hash = '#dashboard';
        return;
      }

      if (!DEV_MODE && page.requiresAuth && !auth.checkAuth()) {
        window.location.hash = '#login';
        return;
      }

      // Render page content using registry (supports async render)
      const maybePromise = page.render();
      const pageContent = maybePromise instanceof Promise ? await maybePromise : maybePromise;

      // Mobile sidebar: backdrop + topbar
      const sidebarBackdrop = document.createElement('div');
      sidebarBackdrop.className = 'sidebar-backdrop';

      const openMobileSidebar = () => {
        sidebar.classList.add('mobile-open');
        sidebarBackdrop.classList.add('visible');
      };
      const closeMobileSidebar = () => {
        sidebar.classList.remove('mobile-open');
        sidebarBackdrop.classList.remove('visible');
      };
      const handleMobileClose = () => closeMobileSidebar();
      document.addEventListener('sidebar:close-mobile', handleMobileClose);
      sidebarBackdrop.addEventListener('click', closeMobileSidebar);

      const mobileTopbar = document.createElement('header');
      mobileTopbar.className = 'mobile-topbar';
      mobileTopbar.innerHTML = /*html*/`
        <button class="mobile-menu-btn" aria-label="Abrir menú">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <line x1="3" y1="12" x2="21" y2="12"/>
            <line x1="3" y1="6" x2="21" y2="6"/>
            <line x1="3" y1="18" x2="21" y2="18"/>
          </svg>
        </button>
        <span class="mobile-topbar-title">${page.name}</span>
      `;
      mobileTopbar.querySelector('.mobile-menu-btn').addEventListener('click', openMobileSidebar);

      // Chain page cleanup with sidebar event listener cleanup
      const pageCleanup = pageContent && typeof pageContent.cleanup === 'function' ? pageContent.cleanup : null;
      currentPageCleanup = () => {
        document.removeEventListener('sidebar:close-mobile', handleMobileClose);
        if (pageCleanup) pageCleanup();
      };

      mainContent.appendChild(mobileTopbar);
      mainContent.appendChild(pageContent);
      layout.appendChild(sidebar);
      layout.appendChild(sidebarBackdrop);
      layout.appendChild(mainContent);
      app.appendChild(layout);
    } else {
      // For login page, no sidebar
      switch (hash) {
        case '#login':
          app.appendChild(renderLoginPage(() => {
            window.location.hash = '#dashboard';
          }));
          break;
        default:
          window.location.hash = '#login';
      }
    }
  }

  window.addEventListener('hashchange', () => navigate(false));
  navigate(true); // Primera navegación sin guard
}
