/* ============================================================
   SEIVA · 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(), 700);
    }, prefersReduced ? 0 : 2400);
  });

  /* ---------- 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 (staggered specimens) ---------- */
  if ("IntersectionObserver" in window && !prefersReduced) {
    const io = new IntersectionObserver((entries, obs) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add("is-visible"); obs.unobserve(e.target); }
      });
    }, { threshold: 0.14, rootMargin: "0px 0px -6% 0px" });

    document.querySelectorAll(".specimens").forEach((grid) => {
      grid.querySelectorAll(".reveal").forEach((el, i) => {
        el.style.transitionDelay = (i % 3) * 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(--green)" : ""
            )
          );
        }
      });
    }, { rootMargin: "-45% 0px -50% 0px" });
    sections.forEach((s) => spy.observe(s));
  }
})();
