/* Shared JS for AAJGC site
   - Lightbox (images)
   - FAQ accordion + question submission (front-end opens mail client)
   - Modal close handlers
*/

/* LIGHTBOX: open when clicking images in .grid or .thumb */
document.addEventListener('click', function(e){
  const t = e.target;
  if(t.matches('.grid img') || t.matches('.thumb') || t.matches('.thumb-row img')){
    const src = t.getAttribute('src');
    const alt = t.getAttribute('alt') || '';
    const lb = document.getElementById('lightbox');
    if(!lb) return;
    const img = lb.querySelector('.lightbox-content img');
    const cap = document.getElementById('lightbox-caption');
    img.src = src;
    cap.textContent = alt;
    lb.style.display = 'flex';
    lb.setAttribute('aria-hidden','false');
    document.body.style.overflow = 'hidden';
  }
});

/* close lightbox on click (close button or background) */
document.addEventListener('click', function(e){
  if(e.target.matches('.lightbox .close') || e.target.matches('.lightbox')){
    const lb = document.getElementById('lightbox');
    if(lb){ lb.style.display='none'; lb.setAttribute('aria-hidden','true'); document.body.style.overflow=''; }
  }
});

/* FAQ accordion */
document.querySelectorAll('.faq-q').forEach(q=>{
  q.addEventListener('click', ()=>{
    const a = q.nextElementSibling;
    const open = a.style.display === 'block';
    document.querySelectorAll('.faq-a').forEach(x=> x.style.display='none');
    a.style.display = open ? 'none' : 'block';
  });
});

/* FAQ submit form: open mail client + show success */
const faqForm = document.getElementById('faq-form');
if(faqForm){
  faqForm.addEventListener('submit', function(e){
    e.preventDefault();
    const name = this.querySelector('[name="name"]').value.trim();
    const email = this.querySelector('[name="email"]').value.trim();
    const question = this.querySelector('[name="question"]').value.trim();
    if(!name || !email || !question){
      alert('Please complete all fields before submitting.');
      return;
    }
    const to = 'aajgc.church@gmail.com';
    const subject = encodeURIComponent('FAQ question from ' + name);
    const body = encodeURIComponent(`Name: ${name}\nEmail: ${email}\n\nQuestion:\n${question}`);
    window.location.href = `mailto:${to}?subject=${subject}&body=${body}`;
    const msg = document.getElementById('faq-success');
    if(msg){ msg.style.display = 'block'; msg.textContent = 'Thanks — your email client should open now to send your question.'; }
    this.reset();
  });
}

/* close modals on ESC */
document.addEventListener('keydown', function(e){
  if(e.key === 'Escape'){
    document.querySelectorAll('.modal, .lightbox').forEach(m=>{
      if(m.style.display === 'flex' || m.style.display === 'block'){ m.style.display = 'none'; m.setAttribute('aria-hidden','true'); }
    });
    document.body.style.overflow = '';
  }
});
