// Layout para páginas de login: inyecta CSS base, aplica tema claro y agrega footer.
(function(){
  const LAYOUT_LOGIN_VERSION = 'layout-login-v1001';
  const CSS_VERSION = '20250827-1037';
  try { console.log('[ESP]', LAYOUT_LOGIN_VERSION); } catch {}

  // Tema: forzar claro
  const THEME_KEY = 'esp_theme';
  function applyTheme(theme) {
    const t = (theme === 'dark') ? 'dark' : 'light';
    document.documentElement.setAttribute('data-bs-theme', t);
    try { localStorage.setItem(THEME_KEY, t); } catch {}
  }
  function initTheme() {
    applyTheme('light');
    try { localStorage.removeItem(THEME_KEY); } catch {}
  }

  function ensureStylesheet() {
    try {
      const exists = document.querySelector('link[href*="assets/css/layout.css"]');
      if (exists) return;
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = `assets/css/layout.css?v=${CSS_VERSION}`;
      document.head.appendChild(link);
    } catch {}
  }
  // Inyectar CSS y tema lo antes posible para evitar FOUC
  ensureStylesheet();
  applyTheme('light');

  function renderFooter() {
    const year = new Date().getFullYear();
    return `
<footer class="site-footer text-center py-3">
  <div class="container small">ESP Project • v1 • ${year}</div>
</footer>`;
  }

  document.addEventListener('DOMContentLoaded', function(){
    // CSS y tema (segunda pasada defensiva)
    ensureStylesheet();
    initTheme();

    const usingPhpLayout = (document.body && document.body.getAttribute('data-layout') === 'php');
    // Footer (sin navbar ni WebSocket en login) - solo si no lo provee el layout PHP
    if (!usingPhpLayout && !document.querySelector('footer.site-footer')) {
      document.body.insertAdjacentHTML('beforeend', renderFooter());
    }

    // Asegurar contenedor de toasts si no existe
    if (!document.getElementById('toast-container')) {
      const toastDiv = document.createElement('div');
      toastDiv.id = 'toast-container';
      toastDiv.className = 'position-fixed bottom-0 end-0 p-3';
      toastDiv.style.zIndex = '11';
      document.body.appendChild(toastDiv);
    }
  });
})();
