
document.addEventListener('DOMContentLoaded', function(){
  const fallbackImage = '/assets/images/sheltaplux-logo.jpeg';
  document.querySelectorAll('img').forEach((img) => {
    if (!img.getAttribute('loading')) {
      img.setAttribute('loading', 'lazy');
    }
    img.addEventListener('error', function onError() {
      if (!img.src.includes(fallbackImage)) {
        img.src = fallbackImage;
      }
      img.removeEventListener('error', onError);
    });
  });

  const nav = document.querySelector('.site-nav');
  const onScroll = () => nav && nav.classList.toggle('scrolled', window.scrollY > 20);
  onScroll();
  window.addEventListener('scroll', onScroll);

  document.querySelectorAll('[data-filter]').forEach(btn => {
    btn.addEventListener('click', () => {
      const filter = btn.dataset.filter;
      document.querySelectorAll('[data-filter]').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      document.querySelectorAll('.project-item').forEach(item => {
        const match = filter === 'all' || item.dataset.category.includes(filter);
        item.style.display = match ? '' : 'none';
      });
    });
  });

  const form = document.getElementById('quoteForm');
  if(form){
    form.addEventListener('submit', async function(e){
      e.preventDefault();
      const status = form.querySelector('.form-status');
      const submitBtn = form.querySelector('button[type="submit"]');
      status.classList.remove('error', 'success');
      status.textContent = 'Sending...';
      submitBtn.disabled = true;

      try {
        const response = await fetch(form.action, {
          method: 'POST',
          headers: {
            'X-Requested-With': 'XMLHttpRequest'
          },
          body: new FormData(form)
        });

        const data = await response.json();
        if (!response.ok || !data.success) {
          status.classList.add('error');
          status.textContent = data.message || 'Unable to send message right now.';
          return;
        }

        status.classList.add('success');
        status.textContent = data.message || 'Message sent successfully.';
        form.reset();
      } catch (err) {
        status.classList.add('error');
        status.textContent = 'Network error. Please try again.';
      } finally {
        submitBtn.disabled = false;
      }
    });
  }
});
