// Contact form submission
document.addEventListener('DOMContentLoaded', function() {
  const contactForm = document.getElementById('contact-form');
  if (contactForm) {
    contactForm.addEventListener('submit', async function(e) {
      e.preventDefault();
      
      const formData = new FormData(contactForm);
      const formMessage = document.getElementById('form-message');
      
      try {
        const response = await fetch('/contact', {
          method: 'POST',
          body: formData
        });
        
        const result = await response.json();
        
        formMessage.style.display = 'block';
        if (result.success) {
          formMessage.style.background = '#d4edda';
          formMessage.style.color = '#155724';
          formMessage.textContent = result.message;
          contactForm.reset();
        } else {
          formMessage.style.background = '#f8d7da';
          formMessage.style.color = '#721c24';
          formMessage.textContent = result.message;
        }
      } catch (error) {
        formMessage.style.display = 'block';
        formMessage.style.background = '#f8d7da';
        formMessage.style.color = '#721c24';
        formMessage.textContent = 'An error occurred. Please try again later.';
      }
    });
  }
});


// Add smooth scrolling for anchor links
document.addEventListener('DOMContentLoaded', function() {
  const links = document.querySelectorAll('a[href^="#"]');
  
  links.forEach(link => {
    link.addEventListener('click', function(e) {
      const href = this.getAttribute('href');
      if (href !== '#') {
        e.preventDefault();
        const target = document.querySelector(href);
        if (target) {
          target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
          });
        }
      }
    });
  });
});

// Load random Bible verse on homepage (if not already loaded)
async function loadRandomBibleVerse() {
  const verseContainer = document.getElementById('random-verse');
  if (verseContainer && !verseContainer.dataset.loaded) {
    try {
      const response = await fetch('https://api.rockvilletollandsda.church/api/bible_verses/random');
      const result = await response.json();
      
      if (result.success && result.data) {
        verseContainer.innerHTML = `
          <blockquote>"${result.data.text}"</blockquote>
          <cite>- ${result.data.reference}</cite>
        `;
        verseContainer.dataset.loaded = 'true';
      }
    } catch (error) {
      console.error('Error loading Bible verse:', error);
    }
  }
}

// Load verse on page load if container exists
document.addEventListener('DOMContentLoaded', loadRandomBibleVerse);