/** 浏览器内事件录制 — 纯 JS，避免 tsx evaluate 注入 __name */
(function installP1HumanRecorder() {
  if (window.__p1RecorderInstalled) return;
  window.__p1RecorderInstalled = true;
  window.__p1HumanEvents = window.__p1HumanEvents || [];

  function pickLabel(el) {
    if (!el || !el.tagName) return "";
    if (el.tagName === "LABEL") {
      return (el.textContent || "").replace(/\s+/g, " ").trim();
    }
    if (el.id) {
      var lbl = document.querySelector('label[for="' + el.id + '"]');
      if (lbl) return (lbl.textContent || "").replace(/\s+/g, " ").trim();
    }
    if (el.labels && el.labels[0]) {
      return (el.labels[0].textContent || "").replace(/\s+/g, " ").trim();
    }
    return "";
  }

  function resolveInteractive(el) {
    var cur = el;
    for (var depth = 0; depth < 10 && cur; depth += 1) {
      if (!cur.tagName) break;
      var tag = cur.tagName.toUpperCase();
      if (tag === "INPUT" && (cur.type === "checkbox" || cur.type === "radio")) return cur;
      if (tag === "LABEL") return cur;
      if (tag === "BUTTON") return cur;
      if (cur.getAttribute && cur.getAttribute("role") === "checkbox") return cur;
      cur = cur.parentElement;
    }
    return el;
  }

  function pushEvent(kind, el) {
    el = resolveInteractive(el);
    if (!el || !el.tagName) return;
    var value = "";
    if (el.tagName === "SELECT" && el.options && el.selectedIndex >= 0) {
      value = (el.options[el.selectedIndex].text || "").trim();
    } else {
      value = String(el.value || "").slice(0, 200);
    }
    window.__p1HumanEvents.push({
      ts: Date.now(),
      kind: kind,
      url: location.href,
      tag: el.tagName.toLowerCase(),
      id: el.id || "",
      name: el.getAttribute("name") || "",
      inputType: el.type || "",
      value: value,
      label: pickLabel(el),
      text: (el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 120),
      selector: el.id ? "#" + el.id : "",
    });
  }

  function bindRoot(root) {
    if (!root || root.__p1RecorderBound) return;
    root.__p1RecorderBound = true;
    root.addEventListener(
      "click",
      function (e) {
        pushEvent("click", e.target);
      },
      true,
    );
    root.addEventListener(
      "change",
      function (e) {
        pushEvent("change", e.target);
      },
      true,
    );
    root.addEventListener(
      "input",
      function (e) {
        if (e.target && e.target.type === "checkbox") return;
        pushEvent("input", e.target);
      },
      true,
    );
  }

  function bindAll() {
    bindRoot(document.querySelector("#container-mh"));
    bindRoot(document.body);
  }

  bindAll();

  var obs = new MutationObserver(function () {
    bindAll();
  });
  obs.observe(document.documentElement, { childList: true, subtree: true });
})();
