document.addEventListener("DOMContentLoaded", function () {
  // Mobile Menu Toggle
  const mobileMenu = document.getElementById("mobile-menu");
  const navLinks = document.getElementById("nav-links");

  mobileMenu.addEventListener("click", () => {
    mobileMenu.classList.toggle("active");
    navLinks.classList.toggle("active");
  });

  // Close mobile menu when clicking a link
  document.querySelectorAll(".nav-links a").forEach((link) => {
    link.addEventListener("click", () => {
      mobileMenu.classList.remove("active");
      navLinks.classList.remove("active");
    });
  });

  // Initialize Swiper
  const swiper = new Swiper(".swiper", {
    loop: true,
    autoplay: {
      delay: 5000,
      disableOnInteraction: false,
    },
    pagination: {
      el: ".swiper-pagination",
      clickable: true,
    },
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    breakpoints: {
      640: {
        slidesPerView: 1,
        spaceBetween: 20,
      },
      768: {
        slidesPerView: 2,
        spaceBetween: 30,
      },
      1024: {
        slidesPerView: 3,
        spaceBetween: 40,
      },
    },
  });

  // Smooth scrolling for navigation links
  document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
    anchor.addEventListener("click", function (e) {
      e.preventDefault();
      document.querySelector(this.getAttribute("href")).scrollIntoView({
        behavior: "smooth",
      });
    });
  });

  // Gallery Lightbox
  const lightbox = document.getElementById("lightbox");
  const lightboxImg = document.getElementById("lightbox-img");
  const caption = document.getElementById("caption");
  const galleryItems = document.querySelectorAll(".gallery-item");
  let currentIndex = 0;

  galleryItems.forEach((item, index) => {
    item.addEventListener("click", () => {
      currentIndex = index;
      const imgSrc = item.querySelector("img").src;
      const imgCaption = item.querySelector("img").getAttribute("data-caption");
      lightboxImg.src = imgSrc;
      caption.textContent = imgCaption;
      lightbox.style.display = "block";
      document.body.style.overflow = "hidden";
    });
  });

  // Lightbox controls
  document.querySelector(".close-btn").addEventListener("click", () => {
    lightbox.style.display = "none";
    document.body.style.overflow = "auto";
  });

  document.querySelector(".prev").addEventListener("click", (e) => {
    e.stopPropagation();
    currentIndex =
      (currentIndex - 1 + galleryItems.length) % galleryItems.length;
    updateLightbox();
  });

  document.querySelector(".next").addEventListener("click", (e) => {
    e.stopPropagation();
    currentIndex = (currentIndex + 1) % galleryItems.length;
    updateLightbox();
  });

  function updateLightbox() {
    const currentImg = galleryItems[currentIndex].querySelector("img");
    lightboxImg.src = currentImg.src;
    caption.textContent = currentImg.getAttribute("data-caption") || "";
  }

  // Close lightbox when clicking outside
  lightbox.addEventListener("click", (e) => {
    if (e.target === lightbox) {
      lightbox.style.display = "none";
      document.body.style.overflow = "auto";
    }
  });

  // Keyboard navigation for lightbox
  document.addEventListener("keydown", (e) => {
    if (lightbox.style.display === "block") {
      if (e.key === "Escape") {
        lightbox.style.display = "none";
        document.body.style.overflow = "auto";
      } else if (e.key === "ArrowLeft") {
        currentIndex =
          (currentIndex - 1 + galleryItems.length) % galleryItems.length;
        updateLightbox();
      } else if (e.key === "ArrowRight") {
        currentIndex = (currentIndex + 1) % galleryItems.length;
        updateLightbox();
      }
    }
  });

  // Form submission
  document
    .getElementById("contactForm")
    ?.addEventListener("submit", function (e) {
      e.preventDefault();
      const formData = new FormData(this);

      fetch(this.action, {
        method: "POST",
        body: formData,
      })
        .then((response) => response.json())
        .then((data) => {
          if (data.success) {
            alert("Thank you for your message! We will get back to you soon.");
            this.reset();
          } else {
            alert("There was an error sending your message. Please try again.");
          }
        })
        .catch((error) => {
          console.error("Error:", error);
          alert("There was an error sending your message. Please try again.");
        });
    });
});
document.getElementById("contactForm").addEventListener("submit", function (e) {
  e.preventDefault();

  // Clear previous errors
  document.querySelectorAll(".error-message").forEach((el) => el.remove());
  document
    .querySelectorAll(".input-error")
    .forEach((el) => el.classList.remove("input-error"));

  // Get form elements
  const form = e.target;
  const formData = new FormData(form);
  const submitBtn = form.querySelector('button[type="submit"]');

  // Disable submit button to prevent multiple submissions
  submitBtn.disabled = true;
  submitBtn.textContent = "Sending...";

  // Client-side validation
  let isValid = true;

  // Name validation
  const name = formData.get("name");
  if (!name || name.length < 2 || name.length > 50) {
    showError(
      form.elements.name,
      "Please enter a valid name (2-50 characters)"
    );
    isValid = false;
  }

  // Email validation
  const email = formData.get("email");
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!email || !emailRegex.test(email)) {
    showError(form.elements.email, "Please enter a valid email address");
    isValid = false;
  }

  // Subject validation (optional)
  const subject = formData.get("subject");
  if (subject && (subject.length < 3 || subject.length > 100)) {
    showError(
      form.elements.subject,
      "Subject must be between 3-100 characters"
    );
    isValid = false;
  }

  // Message validation
  const message = formData.get("message");
  if (!message || message.length < 10 || message.length > 2000) {
    showError(
      form.elements.message,
      "Message must be between 10-2000 characters"
    );
    isValid = false;
  }

  if (!isValid) {
    submitBtn.disabled = false;
    submitBtn.textContent = "Send Message";
    return;
  }

  // Send form data via AJAX
  fetch(form.action, {
    method: "POST",
    body: formData,
    headers: {
      Accept: "application/json",
    },
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.success) {
        // Show success message
        const successMsg = document.createElement("div");
        successMsg.className = "success-message";
        successMsg.textContent = data.message;
        form.parentNode.insertBefore(successMsg, form);
        form.reset();

        // Hide success message after 5 seconds
        setTimeout(() => {
          successMsg.remove();
        }, 5000);
      } else {
        // Show server-side validation errors
        if (data.errors) {
          for (const field in data.errors) {
            showError(form.elements[field], data.errors[field]);
          }
        } else {
          showFormError(data.message || "An error occurred. Please try again.");
        }
      }
    })
    .catch((error) => {
      showFormError("Network error. Please try again.");
    })
    .finally(() => {
      submitBtn.disabled = false;
      submitBtn.textContent = "Send Message";
    });
});

function showError(input, message) {
  const errorElement = document.createElement("div");
  errorElement.className = "error-message";
  errorElement.textContent = message;
  input.classList.add("input-error");
  input.parentNode.insertBefore(errorElement, input.nextSibling);
}

function showFormError(message) {
  const formError = document.createElement("div");
  formError.className = "form-error-message";
  formError.textContent = message;
  const form = document.getElementById("contactForm");
  form.parentNode.insertBefore(formError, form);

  // Hide error after 5 seconds
  setTimeout(() => {
    formError.remove();
  }, 5000);
}
