/* ============================================================
   tracking.js — dataLayer / GTM події (Task 4 §1.3)
   Кожна подія авто-підмішує variant_id, audience_segment,
   traffic_source. Експонує window.KZTrack для form.js.
   ============================================================ */
(function () {
  "use strict";
  var KZ = window.KZ || {};
  var cfg = KZ.config || {};
  window.dataLayer = window.dataLayer || [];

  function getTrafficSource() {
    var p = null;
    try { p = new URLSearchParams(location.search); } catch (e) { p = null; }
    var src = p && (p.get("utm_source") || p.get("utm_campaign"));
    if (src) return src;
    if (document.referrer) {
      try { return new URL(document.referrer).hostname; } catch (e) { /* noop */ }
    }
    return "direct";
  }

  var base = {
    variant_id: cfg.variantId || "v1_price_qualifier",
    audience_segment: cfg.audienceSegment || "default",
    traffic_source: getTrafficSource()
  };

  function push(event, params) {
    var o = { event: event };
    for (var k in base) { if (base.hasOwnProperty(k)) o[k] = base[k]; }
    if (params) { for (var p in params) { if (params.hasOwnProperty(p)) o[p] = params[p]; } }
    window.dataLayer.push(o);
  }

  window.KZTrack = { push: push, base: base };

  function throttle(fn, wait) {
    var last = 0, t = null;
    return function () {
      var now = Date.now();
      if (now - last >= wait) { last = now; fn(); }
      else { clearTimeout(t); t = setTimeout(function () { last = Date.now(); fn(); }, wait); }
    };
  }

  /* page_view */
  push("page_view");

  /* scroll_depth 25/50/75/100 */
  var marks = [25, 50, 75, 100], fired = {};
  function onScroll() {
    var d = document.documentElement;
    var max = d.scrollHeight - window.innerHeight;
    if (max <= 0) return;
    var depth = (d.scrollTop / max) * 100;
    for (var i = 0; i < marks.length; i++) {
      var m = marks[i];
      if (!fired[m] && depth >= m) { fired[m] = 1; push("scroll_depth", { depth: m }); }
    }
  }
  window.addEventListener("scroll", throttle(onScroll, 300), { passive: true });

  /* block_view (+ offer_view для price) через IntersectionObserver */
  var seen = {};
  if ("IntersectionObserver" in window) {
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (e) {
        if (!e.isIntersecting) return;
        var id = e.target.getAttribute("data-block-id");
        if (id && !seen[id]) {
          seen[id] = 1;
          push("block_view", { block_id: id });
          if (id === "price") push("offer_view");
        }
      });
    }, { threshold: 0.4 });
    document.querySelectorAll("[data-block-id]").forEach(function (el) { io.observe(el); });
  }

  /* cta_click (делегування) */
  document.addEventListener("click", function (e) {
    var el = e.target.closest && e.target.closest("[data-cta-id]");
    if (!el) return;
    push("cta_click", {
      cta_id: el.getAttribute("data-cta-id"),
      cta_position: el.getAttribute("data-cta-position") || ""
    });
  });

  /* form_start — перший фокус у формі */
  var form = document.getElementById("leadForm");
  if (form) {
    var started = false;
    form.addEventListener("focusin", function () {
      if (started) return;
      started = true;
      push("form_start");
    });
  }
})();
