const nav = document.getElementById("site-nav");
const toggle = document.querySelector(".nav-toggle");
const headerLinks = [...document.querySelectorAll(".site-nav a")];
const year = document.getElementById("year");
const form = document.getElementById("contact-form");
const lightbox = document.getElementById("lightbox");
const lightboxImg = lightbox.querySelector("img");
const lightboxCaption = lightbox.querySelector(".lightbox-caption");

year.textContent = new Date().getFullYear();

toggle.addEventListener("click", () => {
  const open = nav.classList.toggle("is-open");
  toggle.setAttribute("aria-expanded", String(open));
});

headerLinks.forEach((link) => {
  link.addEventListener("click", () => {
    nav.classList.remove("is-open");
    toggle.setAttribute("aria-expanded", "false");
  });
});

const sections = [...document.querySelectorAll("section[id]")];
const header = document.querySelector(".site-header");
const progress = document.querySelector(".scroll-progress");
const heroVisual = document.querySelector(".hero-visual");
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

const setActive = () => {
  const y = window.scrollY + 120;
  let current = sections[0]?.id;
  for (const section of sections) {
    if (section.offsetTop <= y) current = section.id;
  }
  headerLinks.forEach((link) => {
    link.classList.toggle("is-active", link.getAttribute("href") === `#${current}`);
  });
};

const onScroll = () => {
  setActive();
  header.classList.toggle("is-scrolled", window.scrollY > 12);
  const max = document.documentElement.scrollHeight - window.innerHeight;
  progress.style.width = `${max > 0 ? (window.scrollY / max) * 100 : 0}%`;
  if (!reduceMotion && heroVisual && window.matchMedia("(min-width: 981px)").matches) {
    heroVisual.style.transform = `translateY(${Math.min(window.scrollY * 0.08, 60)}px)`;
  } else if (heroVisual) {
    heroVisual.style.transform = "";
  }
};

window.addEventListener("scroll", onScroll, { passive: true });
onScroll();

const revealEls = [
  ...document.querySelectorAll(
    ".section-head, .profile-grid, .company-intro, .capability-grid article, .company-note, .timeline li, .qual-list article, .cert-card, .contact-grid > *, .tag-pill"
  ),
];

revealEls.forEach((el, i) => {
  el.classList.add("reveal");
  el.style.setProperty("--d", `${(i % 4) * 90}ms`);
});

if (reduceMotion) {
  revealEls.forEach((el) => el.classList.add("is-in"));
} else {
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("is-in");
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.14, rootMargin: "0px 0px -8% 0px" }
  );
  revealEls.forEach((el) => observer.observe(el));
}

document.querySelectorAll("[data-lightbox]").forEach((card) => {
  card.addEventListener("click", () => {
    lightboxImg.src = card.dataset.lightbox;
    lightboxImg.alt = card.dataset.caption || "";
    lightboxCaption.textContent = card.dataset.caption || "";
    lightbox.showModal();
  });
});

lightbox.querySelector(".lightbox-close").addEventListener("click", () => lightbox.close());
lightbox.addEventListener("click", (event) => {
  if (event.target === lightbox) lightbox.close();
});

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const name = String(data.get("name") || "").trim();
  const email = String(data.get("email") || "").trim();
  const phone = String(data.get("phone") || "").trim();
  const message = String(data.get("message") || "").trim();
  const body = [
    `Name: ${name}`,
    `Email: ${email}`,
    phone ? `Telephone: ${phone}` : "",
    "",
    message,
  ]
    .filter(Boolean)
    .join("\n");
  const href = `mailto:dushantha@dushanthaengineering.com?subject=${encodeURIComponent(
    `Website enquiry from ${name}`
  )}&body=${encodeURIComponent(body)}`;
  window.location.href = href;
});
