/* === DRIPBOX v4.1 — Microinteractions + Smart Preload === */

document.addEventListener("DOMContentLoaded", function () {
  // --- Smooth open/close para os <details> ---
  document.querySelectorAll(".mini-affiliate-section details").forEach((el) => {
    el.addEventListener("toggle", () => {
      el.style.transition = "all 0.3s ease";
      el.style.background = el.open ? "#fafafa" : "transparent";
    });
  });

  // --- Hover visual nos botões ---
  const buttons = document.querySelectorAll(".mini-affiliate-buttons a");
  buttons.forEach((btn) => {
    btn.addEventListener("mouseenter", () => {
      btn.style.boxShadow = "0 6px 14px rgba(0,0,0,0.25)";
      btn.style.transform = "translateY(-2px)";
    });
    btn.addEventListener("mouseleave", () => {
      btn.style.boxShadow = "0 3px 8px rgba(0,0,0,0.15)";
      btn.style.transform = "translateY(0)";
    });
  });

  // --- Smart Preload (Lasso-style) ---
  const preloadLinks = document.querySelectorAll(".mini-affiliate-buttons a");
  preloadLinks.forEach((link) => {
    const preloadURL = () => {
      const url = link.getAttribute("href");
      if (url && !link.dataset.preloaded) {
        const preload = document.createElement("link");
        preload.rel = "preload";
        preload.as = "fetch";
        preload.href = url;
        document.head.appendChild(preload);
        link.dataset.preloaded = "true";
      }
    };

    link.addEventListener("mouseover", preloadURL, { passive: true });
    link.addEventListener("touchstart", preloadURL, { passive: true });
  });
});


// === CLICK ANALYTICS ===
document.addEventListener("click", function(e) {
    const btn = e.target.closest(".track-click");
    if (!btn) return;

    const productId = btn.getAttribute("data-product");
    const type = btn.getAttribute("data-type");

    console.log("TRACK CLICK →", { product: productId, type: type });

    fetch('/wp-json/dripbox/v1/track', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            product_id: productId,
            button: type
        })
    }).then(response => response.json())
      .then(data => console.log("TRACK SUCCESS:", data))
      .catch(err => console.log("TRACK ERROR:", err));
});

console.log("✅ DRIPBOX ANALYTICS LOADED");