const body = document.body;
const header = document.querySelector("[data-header]");
const navToggle = document.querySelector(".nav-toggle");
const navLinks = document.querySelectorAll(".site-nav a");
const contactForm = document.querySelector("[data-contact-form]");
const formNote = document.querySelector("[data-form-note]");

const syncHeader = () => {
  header.classList.toggle("is-scrolled", window.scrollY > 24);
};

if (header) {
  syncHeader();
  window.addEventListener("scroll", syncHeader, { passive: true });
}

if (navToggle) {
  navToggle.addEventListener("click", () => {
    const isOpen = navToggle.getAttribute("aria-expanded") === "true";
    navToggle.setAttribute("aria-expanded", String(!isOpen));
    body.classList.toggle("nav-open", !isOpen);
  });
}

navLinks.forEach((link) => {
  link.addEventListener("click", () => {
    navToggle?.setAttribute("aria-expanded", "false");
    body.classList.remove("nav-open");
  });
});

if (contactForm) {
  contactForm.addEventListener("submit", (event) => {
    event.preventDefault();

    const data = new FormData(contactForm);
    const name = data.get("name").trim();
    const email = data.get("email").trim();
    const phone = data.get("phone")?.trim() || "";
    const company = data.get("company")?.trim() || "";
    const project = data.get("project");
    const timeline = data.get("timeline") || "";
    const message = data.get("message").trim();

    const subject = encodeURIComponent(`Project inquiry from ${name}`);
    const lines = [
      `Name: ${name}`,
      `Email: ${email}`,
      phone ? `Phone: ${phone}` : "",
      company ? `Company: ${company}` : "",
      `Project type: ${project}`,
      timeline ? `Timeline: ${timeline}` : "",
      "",
      message,
    ].filter((line) => line !== "");
    const bodyText = encodeURIComponent(lines.join("\n"));

    window.location.href = `mailto:contact@cloudcodinglabs.com?subject=${subject}&body=${bodyText}`;

    if (formNote) {
      formNote.textContent = "Your email app should open with the project details filled in.";
    }
  });
}
