// Per-prospect tracking client. Exposes window.RBTrack.start(token).
// Plain JS (served via Babel pipeline like the other scripts).
(function () {
  var queue = [];
  var started = false;
  var token = '';
  var enterTimes = {};
  var seenSections = {};
  var maxScroll = 0;

  function push(type, section, value) {
    queue.push({ type: type, section: section || null, value: value == null ? null : String(value) });
    if (queue.length >= 12) flush();
  }

  function flush(useBeacon) {
    if (!queue.length) return;
    var batch = queue.splice(0, queue.length);
    var body = JSON.stringify(batch);
    if (useBeacon && navigator.sendBeacon) {
      navigator.sendBeacon('/api/track', new Blob([body], { type: 'application/json' }));
      return;
    }
    fetch('/api/track', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: body,
      keepalive: true,
      credentials: 'same-origin',
    }).catch(function () { /* swallow; tracking is best-effort */ });
  }

  function onScroll() {
    var h = document.documentElement;
    var denom = (h.scrollHeight - h.clientHeight) || 1;
    var pct = Math.round((h.scrollTop || window.scrollY) / denom * 100);
    if (pct > maxScroll) {
      maxScroll = Math.min(100, pct);
      if (maxScroll % 10 === 0) push('scroll_depth', null, maxScroll);
    }
  }

  function attachSectionObserver() {
    var sections = (window.RBData && window.RBData.SECTIONS) || [];
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (e) {
        var id = e.target.id;
        if (e.isIntersecting) {
          enterTimes[id] = Date.now();
          if (seenSections[id]) push('revisit', id);
          else { seenSections[id] = true; push('section_view', id); }
        } else if (enterTimes[id]) {
          var ms = Date.now() - enterTimes[id];
          delete enterTimes[id];
          if (ms > 800) push('section_dwell', id, ms);
        }
      });
    }, { threshold: 0.4 });

    var found = 0;
    sections.forEach(function (s) {
      var el = document.getElementById(s.id);
      if (el) { io.observe(el); found++; }
    });
    return found;
  }

  function waitForSections(tries) {
    if (attachSectionObserver() > 0 || tries <= 0) return;
    setTimeout(function () { waitForSections(tries - 1); }, 200);
  }

  function onClick(ev) {
    var el = ev.target.closest && ev.target.closest('[data-track]');
    if (!el) return;
    var kind = el.getAttribute('data-track');
    if (kind === 'booking') push('booking', null, el.getAttribute('data-track-label') || 'call');
    else if (kind === 'download') push('download', null, el.getAttribute('data-track-label') || 'pdf');
    else push('click', el.getAttribute('data-track-section') || null, kind);
  }

  window.RBTrack = {
    start: function (t) {
      if (started) return;
      started = true;
      token = t || '';
      try {
        if (window.clarity && token) {
          window.clarity('identify', token);
          window.clarity('set', 'prospect', token);
        }
      } catch (e) { /* clarity optional */ }

      push('vault_open', null, token);
      waitForSections(40);
      window.addEventListener('scroll', onScroll, { passive: true });
      document.addEventListener('click', onClick, true);
      setInterval(function () { flush(false); }, 8000);
      document.addEventListener('visibilitychange', function () {
        if (document.visibilityState === 'hidden') flush(true);
      });
      window.addEventListener('pagehide', function () {
        if (maxScroll > 0) push('scroll_depth', null, maxScroll);
        flush(true);
      });
    },
    event: function (type, section, value) { if (started) push(type, section, value); },
  };
})();
