/* ============================================================
   ROUTE 66 BURGERS · interações
   ============================================================ */
(function () {
  "use strict";

  const prefersReduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
  const clamp = (n, a, b) => Math.max(a, Math.min(b, n));
  const easeOut = (t) => 1 - Math.pow(1 - t, 3);

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

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

  /* ============================================================
     Scroll-driven burger assembly
     Each layer flies in from its scattered start (data-x/y/r)
     to its resting place as the section scrolls through the
     viewport. Layers settle bottom-up via data-order.
     ============================================================ */
  const build = document.getElementById("build");
  const burger = document.getElementById("burger");
  const hint = document.getElementById("buildHint");
  const done = document.getElementById("buildDone");
  const layers = burger ? Array.from(burger.querySelectorAll(".layer")) : [];

  const STAGGER = 0.11;   // delay between consecutive layers
  const WINDOW = 0.5;     // how much progress each layer takes to arrive

  function paintBurger() {
    if (!build || !layers.length) return;

    const total = build.offsetHeight - window.innerHeight;
    const rect = build.getBoundingClientRect();
    const p = clamp(-rect.top / total, 0, 1);

    layers.forEach((layer) => {
      const order = +layer.dataset.order;
      const start = order * STAGGER;
      const local = clamp((p - start) / WINDOW, 0, 1);
      const e = easeOut(local);

      const sx = +layer.dataset.x;
      const sy = +layer.dataset.y;
      const sr = +layer.dataset.r;

      const x = sx * (1 - e);
      const y = sy * (1 - e);
      const r = sr * (1 - e);

      layer.style.transform = `translate3d(${x}px, ${y}px, 0) rotate(${r}deg)`;
      layer.style.opacity = clamp(local * 3, 0, 1);
    });

    // hint fades out as the burger comes together; label appears at the end
    if (hint) hint.style.opacity = String(clamp(1 - p * 2, 0, 1));
    if (done) done.classList.toggle("is-shown", p > 0.92);
  }

  let ticking = false;
  function requestPaint() {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => { paintBurger(); ticking = false; });
  }

  if (build && layers.length) {
    if (prefersReduced) {
      // reduced motion: show the finished burger, no scroll choreography
      layers.forEach((l) => { l.style.transform = "none"; l.style.opacity = "1"; });
      if (done) done.classList.add("is-shown");
      if (hint) hint.style.display = "none";
    } else {
      paintBurger();
      window.addEventListener("scroll", requestPaint, { passive: true });
      window.addEventListener("resize", requestPaint);
    }
  }

  /* ---------- Reveal cards & sections ---------- */
  const revealables = document.querySelectorAll(".reveal");
  if ("IntersectionObserver" in window && !prefersReduced) {
    const io = new IntersectionObserver((entries, obs) => {
      entries.forEach((entry, i) => {
        if (entry.isIntersecting) {
          // slight stagger within a batch for a lively cascade
          entry.target.style.transitionDelay = (entry.target.dataset.d || "0") + "ms";
          entry.target.classList.add("is-visible");
          obs.unobserve(entry.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });

    // stagger cards inside each grid
    document.querySelectorAll(".grid").forEach((grid) => {
      grid.querySelectorAll(".reveal").forEach((el, i) => {
        el.dataset.d = String((i % 4) * 80);
      });
    });

    revealables.forEach((el) => io.observe(el));
  } else {
    revealables.forEach((el) => el.classList.add("is-visible"));
  }

  /* ---------- Active nav link ---------- */
  const links = document.querySelectorAll(".links 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(--yellow)" : ""
            )
          );
        }
      });
    }, { rootMargin: "-45% 0px -50% 0px" });
    sections.forEach((s) => spy.observe(s));
  }
})();
