// Minimal helper shortcuts
const $ = (sel, el=document) => el.querySelector(sel);
const $$ = (sel, el=document) => Array.from((el||document).querySelectorAll(sel));

document.addEventListener('DOMContentLoaded', () => {
  // Year
  const y = $('#year'); if (y) y.textContent = new Date().getFullYear();

  // Mobile nav
  const navToggle = $('.nav-toggle');
  const nav = $('.site-nav');
  if (navToggle && nav) navToggle.addEventListener('click', () => nav.classList.toggle('open'));

  // WhatsApp FAB
  const wsp = $('#whatsapp-float');
  if (wsp) {
    if (window.APP_CONFIG?.WHATSAPP_NUMBER) {
      const num = window.APP_CONFIG.WHATSAPP_NUMBER.replace(/[^0-9+]/g,'');
      wsp.href = `https://wa.me/${num.replace('+','')}`;
      wsp.textContent = 'W';
    } else {
      wsp.href = '#';
      wsp.textContent = 'W';
    }
  }

  // Carousels
  $$('.media-carousel, .logo-carousel').forEach(setupCarousel);

  // Gallery lightbox
  const lightbox = $('#lightbox');
  if (lightbox) {
    $$('.gallery img').forEach(img => {
      img.style.cursor = 'zoom-in';
      img.addEventListener('click', () => {
        $('img', lightbox).src = img.src;
        lightbox.style.display = 'flex';
        lightbox.setAttribute('aria-hidden','false');
      });
    });
    const lbClose = $('.lightbox-close');
    if (lbClose) lbClose.addEventListener('click', () => {
      lightbox.style.display = 'none';
      lightbox.setAttribute('aria-hidden','true');
    });
    lightbox.addEventListener('click', e => { if (e.target === lightbox) { lightbox.style.display='none'; lightbox.setAttribute('aria-hidden','true'); } });
  }

  // Forms
  setupForm('#form-convocatorias','convocatorias');
  setupForm('#form-inscripcion','anuncios');
  setupForm('#form-denuncias','denuncias');

  // Denuncia toggle anonymous
  const formDen = $('#form-denuncias');
  if (formDen) setupDenunciaForm();

  // Modal for anuncios
  setupModal();

  // Chatbot floating
  const fab = $('#chatbot-fab'), widget = $('#chatbot'), closeBtn = $('#chatbot-close');
  if (fab && widget) {
    fab.addEventListener('click', () => { widget.classList.toggle('hidden'); widget.classList.contains('hidden') || greetOnce(); });
    closeBtn && closeBtn.addEventListener('click', () => widget.classList.add('hidden'));
  }
});

// Carousel implementation (works for media and logos)
function setupCarousel(root){
  const slides = $('.slides', root);
  const items = $$('.slide', slides);
  const prev = $('.carousel-prev', root);
  const next = $('.carousel-next', root);
  const dots = $('.dots', root);
  let index = 0, timer = null;
  const auto = root.dataset.auto === 'true';
  const interval = Number(root.dataset.interval) || 5000;

  // create dots
  if (dots && items.length>1) {
    items.forEach((_,i) => {
      const btn = document.createElement('button');
      btn.addEventListener('click', () => { index = i; update(); });
      dots.appendChild(btn);
    });
  }

  if (prev) prev.addEventListener('click', () => { index = (index-1+items.length)%items.length; update(); });
  if (next) next.addEventListener('click', () => { index = (index+1)%items.length; update(); });

  root.addEventListener('mouseenter', stop);
  root.addEventListener('mouseleave', play);

  function update(){
    slides.style.transform = `translateX(-${index*100}%)`;
    if (dots) $$('.dots button', root).forEach((b,i)=> b.classList.toggle('active', i===index));
    // autoplay video if present
    items.forEach((it,i)=> {
      const v = it.querySelector('video');
      if (v) i===index ? v.play().catch(()=>{}) : v.pause();
    });
  }
  function play(){ if (auto) { stop(); timer = setInterval(()=> { index = (index+1)%items.length; update(); }, interval); } }
  function stop(){ if (timer) { clearInterval(timer); timer = null; } }

  update(); play();
}

// Modal for anuncios
function setupModal(){
  const modal = $('#modal-inscripcion');
  if (!modal) return;
  const openBtns = $$('.open-modal');
  const closeBtn = $('.modal-close', modal);

  openBtns.forEach(btn => btn.addEventListener('click', () => {
    $('#oportunidad', modal).value = btn.dataset.item || '';
    $('#modal-title', modal).textContent = `Inscripción: ${btn.dataset.item || ''}`;
    modal.classList.remove('hidden'); modal.style.display = 'grid'; modal.setAttribute('aria-hidden','false');
  }));

  const close = () => { modal.style.display='none'; modal.classList.add('hidden'); modal.setAttribute('aria-hidden','true'); };
  closeBtn && closeBtn.addEventListener('click', close);
  modal.addEventListener('click', (e) => { if (e.target === modal) close(); });
}

// Denuncia form toggle
function setupDenunciaForm(){
  const form = $('#form-denuncias'); if (!form) return;
  const chk = $('#anonima'); const datos = $('#datos-personales');
  const toggle = () => {
    const anon = chk.checked;
    datos.style.display = anon ? 'none' : 'grid';
    $$('input[name=nombre],input[name=correo],input[name=telefono],input[name=documento]', form)
      .forEach(inp => anon ? inp.removeAttribute('required') : inp.setAttribute('required',''));
  };
  chk.addEventListener('change', toggle);
  toggle();
}

// Generic form handler
function setupForm(selector, formName){
  const form = $(selector);
  if (!form) return;
  const status = $('.form-status', form);

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    status && (status.textContent = 'Enviando…');
    try {
      const endpoint = window.APP_CONFIG?.FORM_ENDPOINT || '';
      if (!endpoint) throw new Error('FORM_ENDPOINT no configurado (assets/config.js)');

      const data = new FormData(form);
      const payload = Object.fromEntries(data.entries());
      payload._form = formName;

      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      if (!res.ok) throw new Error('Error en envío');
      form.reset();
      status && (status.textContent = '¡Gracias! Recibimos tu información.');
    } catch (err) {
      console.error(err);
      status && (status.textContent = 'Error al enviar. Revisa la configuración.');
    }
  });
}

/* Chatbot helper (greet triggered from chatbot.js) */
function greetOnce(){
  const area = $('#chatbot-messages');
  if (!area) return;
  if (area.dataset.greeted) return;
  area.dataset.greeted = '1';
  const cfg = window.APP_CONFIG?.CHATBOT || {};
  addChatMsg(cfg.GREETING || 'Hola, ¿en qué te ayudo?', 'bot');
  const faq = cfg.FAQ || [];
  if (faq.length) addChatMsg('Preguntas rápidas: ' + faq.map(f=>f[0]).join(' · '), 'bot');
}
function addChatMsg(text, who='bot'){
  const area = $('#chatbot-messages');
  if (!area) return;
  const div = document.createElement('div');
  div.className = 'chatbot-msg ' + (who === 'user' ? 'user' : 'bot');
  div.textContent = text;
  area.appendChild(div);
  area.scrollTop = area.scrollHeight;
}
