import { apiUrl } from "../auth/session.js";

const ALLOWED = new Set(["sponsor", "bonus", "promo"]);

export function trackOutboundClick(kind, itemId, label) {
  const k = String(kind || "").trim();
  if (!ALLOWED.has(k)) return;
  const payload = {
    kind: k,
    itemId: String(itemId ?? "").trim().slice(0, 64),
    label: String(label ?? "").trim().slice(0, 160),
  };
  if (!payload.itemId && !payload.label) return;

  const url = apiUrl("track_click.php");
  const body = JSON.stringify(payload);
  try {
    if (typeof navigator.sendBeacon === "function") {
      navigator.sendBeacon(url, new Blob([body], { type: "application/json" }));
      return;
    }
  } catch {
    /* noop */
  }
  void fetch(url, {
    method: "POST",
    credentials: "omit",
    cache: "no-store",
    keepalive: true,
    headers: { "Content-Type": "application/json" },
    body,
  }).catch(() => {});
}

export function bindTrackClick(root, selector, kind, idAttr, labelAttr) {
  if (!root) return;
  root.querySelectorAll(selector).forEach((el) => {
    el.addEventListener("click", () => {
      trackOutboundClick(
        kind,
        el.getAttribute(idAttr) || "",
        el.getAttribute(labelAttr) || el.textContent?.trim() || "",
      );
    });
  });
}
