// v2-fx.jsx — premium motion layer: magnetic buttons + scroll parallax
// Plain JS (loaded via babel). Self-initializing; no-ops when body lacks .fx-on.

(function () {
  const FX_OK =
    window.matchMedia("(pointer: fine)").matches &&
    !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  window.__FX_OK = FX_OK;
  if (!FX_OK) return;

  const MAG_SEL = ".cta-gold, .line-link, .box-link";
  let magEl = null;

  const active = () => document.body.classList.contains("fx-on");

  // ── hover-video on work cards ────────────────────────────────
  document.addEventListener("mouseover", (e) => {
    const c = e.target.closest(".work-card");
    if (!c) return;
    const v = c.querySelector(".plate-video");
    if (v && v.paused) { v.currentTime = 0; v.play().catch(() => {}); }
  }, { passive: true });
  document.addEventListener("mouseout", (e) => {
    const c = e.target.closest(".work-card");
    if (!c || c.contains(e.relatedTarget)) return;
    const v = c.querySelector(".plate-video");
    if (v) v.pause();
  }, { passive: true });

  // ── magnetic buttons ─────────────────────────────────────────
  document.addEventListener("mousemove", (e) => {
    if (!active()) return;
    const el = e.target.closest(MAG_SEL);
    if (el !== magEl) { if (magEl) magEl.style.transform = ""; magEl = el; }
    if (el) {
      const r = el.getBoundingClientRect();
      const ox = e.clientX - (r.left + r.width / 2);
      const oy = e.clientY - (r.top + r.height / 2);
      el.style.transform = `translate(${ox * 0.22}px, ${oy * 0.30}px)`;
    }
  }, { passive: true });

  // ── render loop: scroll parallax on renders ──────────────────
  const AMP = 16; // px of parallax travel
  function frame() {
    if (active()) {
      const vh = innerHeight;
      const photos = document.querySelectorAll(".plate-photo, .plate-img");
      for (let i = 0; i < photos.length; i++) {
        const img = photos[i];
        const r = img.getBoundingClientRect();
        if (r.bottom < -40 || r.top > vh + 40) continue;
        const rel = (r.top + r.height / 2 - vh / 2) / vh; // ~ -0.5..0.5
        const shift = -rel * AMP;
        const card = img.closest(".work-card");
        const hov = card && card.matches(":hover");
        if (img.__s == null) img.__s = 1.06;
        img.__s += ((hov ? 1.12 : 1.06) - img.__s) * 0.12;
        img.style.transform = `translate3d(0, ${shift.toFixed(2)}px, 0) scale(${img.__s.toFixed(4)})`;
      }
    }
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);

  // when FX turns off, clear inline transforms so CSS resumes
  const obs = new MutationObserver(() => {
    if (!active()) {
      if (magEl) { magEl.style.transform = ""; magEl = null; }
      document.querySelectorAll(".plate-photo, .plate-img").forEach(img => { img.style.transform = ""; img.__s = null; });
    }
  });
  obs.observe(document.body, { attributes: true, attributeFilter: ["class"] });
})();
