/* ============================================================
   NÈVE · interações
   ============================================================ */
(function () {
  "use strict";

  const prefersReduced = matchMedia("(prefers-reduced-motion: reduce)").matches;

  /* ---------- Opening animation ---------- */
  const intro = document.getElementById("intro");
  window.addEventListener("load", () => {
    setTimeout(() => {
      if (intro) intro.classList.add("is-done");
      document.body.classList.remove("is-loading");
      setTimeout(() => intro && intro.remove(), 800);
    }, prefersReduced ? 0 : 2200);
  });

  /* ---------- Header state ---------- */
  const head = document.getElementById("head");
  const onScroll = () => head.classList.toggle("is-scrolled", window.scrollY > 40);
  onScroll();
  window.addEventListener("scroll", onScroll, { passive: true });

  /* ---------- Reveal on scroll ---------- */
  if ("IntersectionObserver" in window && !prefersReduced) {
    const io = new IntersectionObserver((entries, obs) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("is-visible");
          obs.unobserve(entry.target);
        }
      });
    }, { threshold: 0.15, rootMargin: "0px 0px -6% 0px" });

    // gentle stagger inside the flavour gallery & formats
    document.querySelectorAll(".gallery, .formats").forEach((grid) => {
      grid.querySelectorAll(".reveal").forEach((el, i) => {
        el.style.transitionDelay = (i % 4) * 90 + "ms";
      });
    });
    document.querySelectorAll(".reveal").forEach((el) => io.observe(el));
  } else {
    document.querySelectorAll(".reveal").forEach((el) => el.classList.add("is-visible"));
  }

  /* ---------- Active nav link ---------- */
  const links = document.querySelectorAll(".nav a");
  const sections = document.querySelectorAll("main section[id]");
  if ("IntersectionObserver" in window && links.length) {
    const spy = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          links.forEach((a) =>
            a.style.setProperty(
              "color",
              a.getAttribute("href") === "#" + entry.target.id ? "var(--terra)" : ""
            )
          );
        }
      });
    }, { rootMargin: "-45% 0px -50% 0px" });
    sections.forEach((s) => spy.observe(s));
  }
})();
