/**
 * Grok-Guide: capture labeled clicks + long hovers (data-jl-help only).
 * Never scrapes free text from the page — only data-jl-help / data-jl-help-detail.
 */
(function () {
  if (window.jlGrokGuide) return;

  var HOVER_MS = 2500;
  var clicks = [];
  var hovers = [];
  var hoverTimers = new WeakMap();

  function pushRing(arr, item, max) {
    arr.push(item);
    while (arr.length > max) arr.shift();
  }

  function labelFrom(el) {
    if (!el || !el.getAttribute) return null;
    var node = el.closest ? el.closest('[data-jl-help]') : null;
    if (!node) return null;
    var label = node.getAttribute('data-jl-help');
    if (!label) return null;
    var detail = node.getAttribute('data-jl-help-detail') || null;
    return { label: label, detail: detail };
  }

  document.addEventListener(
    'click',
    function (e) {
      try {
        var info = labelFrom(e.target);
        if (!info) return;
        pushRing(clicks, {
          label: info.label,
          detail: info.detail,
          t: Date.now()
        }, 12);
      } catch (_) {}
    },
    true
  );

  document.addEventListener(
    'pointerenter',
    function (e) {
      try {
        var info = labelFrom(e.target);
        if (!info) return;
        var node = e.target.closest('[data-jl-help]');
        if (!node) return;
        var start = Date.now();
        hoverTimers.set(node, start);
      } catch (_) {}
    },
    true
  );

  document.addEventListener(
    'pointerleave',
    function (e) {
      try {
        var node = e.target && e.target.closest ? e.target.closest('[data-jl-help]') : null;
        if (!node || !hoverTimers.has(node)) return;
        var start = hoverTimers.get(node);
        hoverTimers.delete(node);
        var ms = Date.now() - start;
        if (ms < HOVER_MS) return;
        var label = node.getAttribute('data-jl-help');
        var detail = node.getAttribute('data-jl-help-detail') || null;
        if (!label) return;
        pushRing(hovers, { label: label, detail: detail, ms: ms, t: Date.now() }, 8);
      } catch (_) {}
    },
    true
  );

  window.jlGrokGuide = {
    drain: function () {
      var payload = {
        clicks: clicks.slice(),
        hovers: hovers.slice()
      };
      clicks = [];
      hovers = [];
      return JSON.stringify(payload);
    },
    peek: function () {
      return JSON.stringify({ clicks: clicks, hovers: hovers });
    }
  };
})();
