(() => {
  const C = window.SITE_CONFIG || {};
  const current = (location.pathname.split('/').pop() || 'index.html').toLowerCase();

  const icon = (name) => {
    const icons = {
      home:'<path d="M3 11.5 12 4l9 7.5"/><path d="M5 10.5V21h14V10.5"/><path d="M9 21v-6h6v6"/>',
      school:'<path d="m3 10 9-6 9 6"/><path d="M5 9v11h14V9"/><path d="M9 20v-6h6v6"/><path d="M8 11h.01M12 11h.01M16 11h.01"/>',
      quality:'<path d="m12 3 2.6 5.3 5.9.9-4.3 4.2 1 5.9-5.2-2.8-5.2 2.8 1-5.9-4.3-4.2 5.9-.9Z"/>',
      people:'<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>',
      laptop:'<rect x="3" y="4" width="18" height="12" rx="2"/><path d="M2 20h20M8 20l1-4h6l1 4"/>',
      chart:'<path d="M4 19V9M10 19V5M16 19v-8M22 19V2"/><path d="M2 19h22"/>',
      book:'<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M4 4v15.5"/><path d="M20 22V4H6.5A2.5 2.5 0 0 0 4 6.5v13"/>',
      news:'<path d="M4 4h16v16H4z"/><path d="M8 8h8M8 12h8M8 16h5"/>',
      gallery:'<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/>',
      mail:'<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
      contact:'<path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4Z"/>',
      whatsapp:'<path d="M20.5 11.7a8.5 8.5 0 0 1-12.6 7.4L3 20.5l1.4-4.7A8.5 8.5 0 1 1 20.5 11.7Z"/><path d="M8.2 7.7c.2-.5.4-.5.8-.5h.5c.2 0 .4.1.5.4l.7 1.7c.1.3.1.5-.1.7l-.6.8c-.2.2-.1.4 0 .6.7 1.3 1.7 2.3 3 3 .2.1.4.2.6 0l.9-1c.2-.2.4-.3.7-.2l1.8.8c.3.1.4.3.4.5 0 .4-.2 1.5-1 2-.7.6-1.7.8-2.7.5-1.2-.3-2.7-1-4.4-2.5-1.4-1.3-2.5-2.8-3-4.2-.5-1.4 0-2.3.4-2.8.4-.4.8-.6 1.5-.6"/>',
      doc:'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6M8 13h8M8 17h8M8 9h2"/>',
      network:'<circle cx="12" cy="12" r="3"/><circle cx="5" cy="5" r="2"/><circle cx="19" cy="5" r="2"/><circle cx="5" cy="19" r="2"/><circle cx="19" cy="19" r="2"/><path d="m7 7 3 3m4 0 3-3m-7 7-3 3m7-3 3 3"/>',
      calendar:'<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 11h18"/>',
      pin:'<path d="M20 10c0 5-8 12-8 12S4 15 4 10a8 8 0 1 1 16 0Z"/><circle cx="12" cy="10" r="3"/>',
      phone:'<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.35 1.9.66 2.8a2 2 0 0 1-.45 2.11L8.05 9.9a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.9.31 1.84.53 2.8.66A2 2 0 0 1 22 16.92Z"/>',
      menu:'<path d="M4 6h16M4 12h16M4 18h16"/>',
      close:'<path d="M18 6 6 18M6 6l12 12"/>',
      external:'<path d="M15 3h6v6M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>'
    };
    return `<svg viewBox="0 0 24 24" aria-hidden="true">${icons[name] || icons.doc}</svg>`;
  };

  const cleanWhatsAppNumber = String(C.whatsappNumber || '').replace(/\D/g, '');
  const whatsappUrl = cleanWhatsAppNumber
    ? `https://wa.me/${cleanWhatsAppNumber}?text=${encodeURIComponent(C.whatsappMessage || 'Hola, necesito información institucional.')}`
    : '#';

  const menu = [
    {label:'Inicio', href:'index.html', icon:'home'},
    {label:'Organización Escolar', href:'organizacion-escolar.html', icon:'school', children:[
      ['Identidad institucional','organizacion-escolar.html#identidad'],
      ['Reseña histórica','organizacion-escolar.html#historia'],
      ['Autoridades y organigrama','organizacion-escolar.html#autoridades'],
      ['Unidades y departamentos','organizacion-escolar.html#unidades'],
      ['Datos del plantel','organizacion-escolar.html#datos']
    ]},
    {label:'Calidad Educativa', href:'calidad-educativa.html', icon:'quality', children:[
      ['Transformación pedagógica','calidad-educativa.html#transformacion'],
      ['PIC y PEIC','calidad-educativa.html#proyectos'],
      ['Plan de estudios','calidad-educativa.html#plan-estudios'],
      ['Evaluación y control','calidad-educativa.html#evaluacion'],
      ['Indicadores y mejora','calidad-educativa.html#indicadores']
    ]},
    {label:'Comunidad Educativa', href:'comunidad-educativa.html', icon:'people', children:[
      ['Estudiantes','comunidad-educativa.html#estudiantes'],
      ['Familias y representantes','comunidad-educativa.html#familias'],
      ['Personal institucional','comunidad-educativa.html#personal'],
      ['Consejo Educativo','comunidad-educativa.html#consejo'],
      ['Paz y convivencia','comunidad-educativa.html#convivencia']
    ]},
    {label:'SIAPA', href:'siapa.html', icon:'laptop', accent:true, children:[
      ['Información de SIAPA','siapa.html'],
      ['Ingresar al sistema SIAPA', C.siapaUrl || 'siapa/'],
      ['Módulos y funcionamiento','siapa.html#modulos'],
      ['Instalación y soporte','siapa.html#soporte']
    ]},
    {label:'SIEDI', href:'siedi.html', icon:'chart', accent:true, children:[
      ['Información de SIEDI','siedi.html'],
      ['Ingresar al sistema SIEDI', C.siediUrl || '#'],
      ['Procesos de evaluación','siedi.html#procesos'],
      ['Soporte SIEDI','siedi.html#soporte']
    ]},
    {label:'Formación', href:'formacion.html', icon:'book', children:[
      ['Formación docente','formacion.html#docente'],
      ['Investigación educativa','formacion.html#investigacion'],
      ['Grupos de participación','formacion.html#grupos'],
      ['Ciencia y tecnología','formacion.html#ciencia'],
      ['Todas las Manos a la Siembra','formacion.html#siembra']
    ]},
    {label:'Aula Virtual', href:'aula-virtual.html', icon:'book', accent:true, children:[
      ['Ingresar al aula','aula-virtual.html#acceso'],
      ['Aulas por año','aula-virtual.html#aulas'],
      ['Recursos académicos','aula-virtual.html#recursos'],
      ['Ayuda y tutoriales','aula-virtual.html#ayuda']
    ]},
    {label:'Noticias', href:'noticias.html', icon:'news'},
    {label:'Galería', href:'galeria.html', icon:'gallery'},
    {label:'Redes', href:'redes.html', icon:'network'},
    {label:'Correo', href:'correo.html', icon:'mail', children:[
      ['Información del correo','correo.html'],
      ['Registrar cuenta docente', C.correoRegistroUrl || 'correo-docente/'],
      ['Revisar Webmail cPanel', C.webmailUrl || 'https://uenalbertosmith.com:2096/'],
      ['Directorio institucional','correo.html#directorio'],
      ['Seguridad y 2FA','correo.html#seguridad']
    ]},
    {label:'Contacto', href:'contacto.html', icon:'contact'}
  ];

  const isExternal = href => /^https?:\/\//i.test(href || '');
  const linkAttrs = href => isExternal(href) ? ' target="_blank" rel="noopener noreferrer"' : '';

  const makeNavItem = (item) => {
    const isActive = current === item.href.toLowerCase();
    const sub = item.children ? `<div class="submenu" role="menu">${item.children.map(([l,h]) => `<a href="${h}" role="menuitem"${linkAttrs(h)}>${l}${isExternal(h) ? icon('external') : ''}</a>`).join('')}</div>` : '';
    return `<div class="nav-item ${item.children?'has-submenu':''} ${item.accent?'nav-accent':''}">
      <a class="nav-link ${isActive?'active':''}" href="${item.href}" ${item.children?'aria-haspopup="true"':''}>${icon(item.icon)}<span>${item.label}</span>${item.children?'<span class="chevron">⌄</span>':''}</a>${sub}
    </div>`;
  };

  const header = document.getElementById('site-header');
  if (header) {
    header.innerHTML = `
      <a class="skip-link" href="#contenido">Saltar al contenido</a>
      <div class="topbar"><div class="container topbar-inner">
        <span>${icon('pin')} Villa de Cura, estado Aragua</span>
        <span>${icon('phone')} ${C.phone || '0244-3862599'}</span>
        <a class="top-whatsapp" href="${whatsappUrl}" target="_blank" rel="noopener noreferrer">${icon('whatsapp')} WhatsApp institucional</a>
        <div class="top-actions">
          <button class="icon-button" id="contrastToggle" title="Alto contraste" aria-label="Activar alto contraste">◐</button>
          <button class="icon-button" id="fontToggle" title="Aumentar texto" aria-label="Aumentar tamaño del texto">A+</button>
          <a href="documentos.html">${icon('doc')} Documentos</a>
        </div>
      </div></div>
      <div class="brandbar"><div class="container brandbar-inner">
        <a class="brand" href="index.html" aria-label="Inicio U.E.N. Alberto Smith">
          <img src="assets/img/logo.png" alt="Escudo de la U.E.N. Alberto Smith">
          <div><strong>U.E.N. ALBERTO SMITH</strong><span>Formación integral · Paz · Calidad educativa</span></div>
        </a>
        <div class="quick-portals">
          <a class="portal-btn siapa" href="${C.siapaUrl || 'siapa/'}">${icon('laptop')}<span><b>SIAPA</b><small>Administración escolar</small></span></a>
          <a class="portal-btn siedi" href="${C.siediUrl || '#'}"${linkAttrs(C.siediUrl)}>${icon('chart')}<span><b>SIEDI</b><small>Evaluación institucional</small></span></a>
          <a class="portal-btn aula" href="${C.aulaUrl || 'aula-virtual.html'}">${icon('book')}<span><b>Aula Virtual</b><small>Aprendizaje en línea</small></span></a>
          <a class="portal-btn correo" href="${C.correoUrl || 'correo.html'}">${icon('mail')}<span><b>Correo</b><small>Registro y Webmail</small></span></a>
        </div>
        <button class="mobile-toggle" id="mobileToggle" aria-label="Abrir menú" aria-expanded="false">${icon('menu')}</button>
      </div></div>
      <nav class="mainnav" id="mainNav" aria-label="Navegación principal"><div class="container nav-scroll">${menu.map(makeNavItem).join('')}</div></nav>
    `;
  }

  const footer = document.getElementById('site-footer');
  if (footer) {
    footer.innerHTML = `
      <div class="footer-main"><div class="container footer-grid">
        <section><div class="footer-brand"><img src="assets/img/logo.png" alt=""><div><b>U.E.N. Alberto Smith</b><span>Villa de Cura, estado Aragua</span></div></div><p>Institución comprometida con una educación integral, humanista, participativa y vinculada con la comunidad.</p></section>
        <section><h2>Sistemas institucionales</h2><a href="${C.siapaUrl || 'siapa/'}">Ingresar a SIAPA</a><a href="${C.siediUrl || '#'}"${linkAttrs(C.siediUrl)}>Ingresar a SIEDI</a><a href="aula-virtual.html">Aula Virtual</a><a href="correo.html">Correo institucional</a><a href="${C.correoRegistroUrl || 'correo-docente/'}">Registro docente</a><a href="${C.webmailUrl || 'https://uenalbertosmith.com:2096/'}"${linkAttrs(C.webmailUrl)}>Webmail cPanel</a></section>
        <section><h2>Institución</h2><a href="organizacion-escolar.html#historia">Reseña histórica</a><a href="organizacion-escolar.html#identidad">Misión y visión</a><a href="comunidad-educativa.html#convivencia">Acuerdos de convivencia</a><a href="documentos.html">Documentos y trámites</a></section>
        <section><h2>Contacto</h2><p>${C.address || ''}</p><p>${C.phone || ''}</p><p><a href="mailto:${C.email || ''}">${C.email || ''}</a></p><p><a href="${whatsappUrl}" target="_blank" rel="noopener noreferrer">WhatsApp: ${C.whatsappDisplay || C.phone || ''}</a></p><div class="social-links"><a href="${C.social?.instagram || '#'}" aria-label="Instagram">IG</a><a href="${C.social?.facebook || '#'}" aria-label="Facebook">FB</a><a href="${C.social?.youtube || '#'}" aria-label="YouTube">YT</a></div></section>
      </div></div>
      <div class="footer-bottom"><div class="container"><span>© <span id="year"></span> U.E.N. Alberto Smith. Portal institucional.</span><span><a href="politica-privacidad.html">Privacidad</a> · <a href="accesibilidad.html">Accesibilidad</a></span></div></div>
    `;
  }

  // Applies configurable URLs to static cards and buttons.
  document.querySelectorAll('[data-config-link]').forEach(link => {
    const key = link.getAttribute('data-config-link');
    if (C[key]) {
      link.href = C[key];
      if (isExternal(C[key])) {
        link.target = '_blank';
        link.rel = 'noopener noreferrer';
      }
    }
  });
  document.querySelectorAll('[data-whatsapp-link]').forEach(link => {
    link.href = whatsappUrl;
    link.target = '_blank';
    link.rel = 'noopener noreferrer';
  });

  if (cleanWhatsAppNumber) {
    document.body.insertAdjacentHTML('beforeend', `
      <a class="whatsapp-float" href="${whatsappUrl}" target="_blank" rel="noopener noreferrer" aria-label="Abrir WhatsApp institucional" title="WhatsApp institucional">
        ${icon('whatsapp')}<span>WhatsApp</span>
      </a>
    `);
  }

  document.getElementById('year')?.append(new Date().getFullYear());

  const mobileToggle = document.getElementById('mobileToggle');
  const mainNav = document.getElementById('mainNav');
  mobileToggle?.addEventListener('click', () => {
    const open = mainNav.classList.toggle('open');
    mobileToggle.setAttribute('aria-expanded', String(open));
    mobileToggle.innerHTML = icon(open ? 'close' : 'menu');
  });

  document.querySelectorAll('.has-submenu > .nav-link').forEach(link => {
    link.addEventListener('click', e => {
      if (window.innerWidth <= 1100) {
        const parent = link.parentElement;
        if (!parent.classList.contains('expanded')) {
          e.preventDefault();
          document.querySelectorAll('.nav-item.expanded').forEach(n => n !== parent && n.classList.remove('expanded'));
          parent.classList.add('expanded');
        }
      }
    });
  });

  document.getElementById('contrastToggle')?.addEventListener('click', () => {
    document.documentElement.classList.toggle('high-contrast');
    localStorage.setItem('uen-contrast', document.documentElement.classList.contains('high-contrast') ? '1' : '0');
  });
  document.getElementById('fontToggle')?.addEventListener('click', () => {
    document.documentElement.classList.toggle('large-text');
    localStorage.setItem('uen-font', document.documentElement.classList.contains('large-text') ? '1' : '0');
  });
  if (localStorage.getItem('uen-contrast') === '1') document.documentElement.classList.add('high-contrast');
  if (localStorage.getItem('uen-font') === '1') document.documentElement.classList.add('large-text');

  const observer = 'IntersectionObserver' in window ? new IntersectionObserver(entries => {
    entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('visible'); observer.unobserve(e.target); } });
  }, {threshold:.08}) : null;
  document.querySelectorAll('.reveal').forEach(el => observer ? observer.observe(el) : el.classList.add('visible'));

  document.querySelectorAll('.accordion-button').forEach(btn => btn.addEventListener('click', () => {
    const expanded = btn.getAttribute('aria-expanded') === 'true';
    btn.setAttribute('aria-expanded', String(!expanded));
    const panel = document.getElementById(btn.getAttribute('aria-controls'));
    if (panel) panel.hidden = expanded;
  }));

  const lightbox = document.getElementById('lightbox');
  document.querySelectorAll('[data-lightbox]').forEach(img => img.addEventListener('click', () => {
    if (!lightbox) return;
    lightbox.querySelector('img').src = img.getAttribute('data-full') || img.src;
    lightbox.querySelector('img').alt = img.alt;
    lightbox.classList.add('open');
    lightbox.setAttribute('aria-hidden','false');
  }));
  lightbox?.addEventListener('click', e => { if (e.target === lightbox || e.target.closest('.lightbox-close')) { lightbox.classList.remove('open'); lightbox.setAttribute('aria-hidden','true'); } });

  document.querySelector('#contactForm')?.addEventListener('submit', e => {
    e.preventDefault();
    const status = document.getElementById('formStatus');
    if (status) status.innerHTML = '<strong>Formulario preparado.</strong> Para recibir mensajes reales, configure el correo o el script PHP indicado en README-INSTALACION.txt.';
  });
})();
