// Main JavaScript for Sigma Healthcare Website - Laboratory Equipment & Diagnostics

document.addEventListener('DOMContentLoaded', function() {
    
  // Smooth scrolling for anchor links
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
      anchor.addEventListener('click', function (e) {
          e.preventDefault();
          const target = document.querySelector(this.getAttribute('href'));
          if (target) {
              target.scrollIntoView({
                  behavior: 'smooth',
                  block: 'start'
              });
          }
      });
  });
  
  // Header scroll effect
  window.addEventListener('scroll', function() {
      const header = document.querySelector('.header');
      if (window.scrollY > 100) {
          header.style.background = 'rgba(255, 255, 255, 0.98)';
          header.style.boxShadow = '0 15px 35px rgba(0,0,0,0.15)';
      } else {
          header.style.background = 'rgba(255, 255, 255, 0.95)';
          header.style.boxShadow = '0 10px 30px rgba(0,0,0,0.1)';
      }
  });
  
  // Search functionality
  const searchInput = document.querySelector('.search-input');
  const searchBtn = document.querySelector('.search-btn');
  
  if (searchBtn) {
      searchBtn.addEventListener('click', function(e) {
          e.preventDefault();
          const searchTerm = searchInput.value.trim();
          if (searchTerm) {
              // Implement product search functionality for laboratory equipment
              console.log('Searching for laboratory products:', searchTerm);
              // You can redirect to a search results page or filter products
          }
      });
  }
  
  if (searchInput) {
      searchInput.addEventListener('keypress', function(e) {
          if (e.key === 'Enter') {
              searchBtn.click();
          }
      });
  }
  
  // Newsletter form submission
  const newsletterForm = document.querySelector('.newsletter-form');
  if (newsletterForm) {
      newsletterForm.addEventListener('submit', function(e) {
          e.preventDefault();
          const email = this.querySelector('.newsletter-input').value;
          if (email && isValidEmail(email)) {
              // Handle newsletter subscription
              alert('Thank you for subscribing to our newsletter!');
              this.querySelector('.newsletter-input').value = '';
          } else {
              alert('Please enter a valid email address.');
          }
      });
  }
  
  // Contact form submission
  const contactForm = document.getElementById('contactForm');
  if (contactForm) {
      contactForm.addEventListener('submit', function(e) {
          e.preventDefault();
          
          // Get form data
          const formData = new FormData(this);
          const data = Object.fromEntries(formData);
          
          // Basic validation
          if (validateContactForm(data)) {
              // Here you would normally send the data to your server
              // For demo purposes, we'll just show an alert
              alert('Thank you for your message! We will get back to you soon.');
              this.reset();
          }
      });
  }
  
  // Product filter functionality
  const filterTabs = document.querySelectorAll('.filter-tabs .nav-link');
  filterTabs.forEach(tab => {
      tab.addEventListener('click', function(e) {
          e.preventDefault();
          
          // Remove active class from all tabs
          filterTabs.forEach(t => t.classList.remove('active'));
          // Add active class to clicked tab
          this.classList.add('active');
          
          // Filter products based on selected category
          const category = this.textContent.trim();
          filterProducts(category);
      });
  });
  
  // Animate elements on scroll
  const observerOptions = {
      threshold: 0.1,
      rootMargin: '0px 0px -50px 0px'
  };
  
  const observer = new IntersectionObserver(function(entries) {
      entries.forEach(entry => {
          if (entry.isIntersecting) {
              entry.target.style.opacity = '1';
              entry.target.style.transform = 'translateY(0)';
          }
      });
  }, observerOptions);
  
  // Observe elements with animation classes
  document.querySelectorAll('.fade-in, .slide-in-left, .slide-in-right').forEach(el => {
      el.style.opacity = '0';
      el.style.transform = 'translateY(20px)';
      el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
      observer.observe(el);
  });
  
  // Product quantity controls (for product pages)
  const qtyMinusButtons = document.querySelectorAll('.qty-minus');
  const qtyPlusButtons = document.querySelectorAll('.qty-plus');
  
  qtyMinusButtons.forEach(btn => {
      btn.addEventListener('click', function() {
          const input = this.nextElementSibling;
          const currentValue = parseInt(input.value);
          if (currentValue > 1) {
              input.value = currentValue - 1;
          }
      });
  });
  
  qtyPlusButtons.forEach(btn => {
      btn.addEventListener('click', function() {
          const input = this.previousElementSibling;
          const currentValue = parseInt(input.value);
          input.value = currentValue + 1;
      });
  });
  
});

// Helper Functions
function isValidEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

function validateContactForm(data) {
  if (!data.first_name || data.first_name.trim().length < 2) {
      alert('Please enter a valid first name.');
      return false;
  }
  
  if (!data.last_name || data.last_name.trim().length < 2) {
      alert('Please enter a valid last name.');
      return false;
  }
  
  if (!data.email || !isValidEmail(data.email)) {
      alert('Please enter a valid email address.');
      return false;
  }
  
  if (!data.phone || data.phone.trim().length < 8) {
      alert('Please enter a valid phone number.');
      return false;
  }
  
  if (!data.message || data.message.trim().length < 10) {
      alert('Please enter a message with at least 10 characters.');
      return false;
  }
  
  return true;
}

function filterProducts(category) {
  // Filter laboratory products based on category (Forensic, Virology, Histology, etc.)
  console.log('Filtering laboratory products by category:', category);
  
  // You could hide/show products, make AJAX calls to load filtered products, etc.
}

// Add to cart functionality for laboratory equipment
function addToCart(productId, quantity = 1) {
  // Handle adding laboratory products to cart
  console.log(`Adding laboratory product ${productId} to cart, quantity: ${quantity}`);
  
  // You could store cart data in localStorage, send to server, etc.
  let cart = JSON.parse(localStorage.getItem('cart') || '[]');
  
  const existingItem = cart.find(item => item.id === productId);
  if (existingItem) {
      existingItem.quantity += quantity;
  } else {
      cart.push({ id: productId, quantity: quantity });
  }
  
  localStorage.setItem('cart', JSON.stringify(cart));
  
  // Show success message for laboratory product
  showNotification('Laboratory product added to cart successfully!', 'success');
}

// Show notification function
function showNotification(message, type = 'info') {
  const notification = document.createElement('div');
  notification.className = `alert alert-${type} notification`;
  notification.textContent = message;
  notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 9999;
      min-width: 300px;
      opacity: 0;
      transform: translateX(100%);
      transition: all 0.3s ease;
  `;
  
  document.body.appendChild(notification);
  
  // Animate in
  setTimeout(() => {
      notification.style.opacity = '1';
      notification.style.transform = 'translateX(0)';
  }, 100);
  
  // Remove after 3 seconds
  setTimeout(() => {
      notification.style.opacity = '0';
      notification.style.transform = 'translateX(100%)';
      setTimeout(() => {
          notification.remove();
      }, 300);
  }, 3000);
}

// Initialize tooltips and popovers if using Bootstrap
document.addEventListener('DOMContentLoaded', function() {
  // Initialize Bootstrap tooltips
  var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
  var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl);
  });
  
  // Initialize Bootstrap popovers
  var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
  var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
      return new bootstrap.Popover(popoverTriggerEl);
  });
});