/**
 * document_start：在 B 站页面脚本之前拦截标签槽 pointerdown（含 Shadow DOM）
 */
(function () {
  "use strict";
  if (window.self !== window.top) return;
  if (window.__biliindexSlotPointer) return;
  window.__biliindexSlotPointer = true;
  const markReady = () => {
    document.documentElement?.setAttribute("data-biliindex-slot-pointer-early", "1");
  };
  if (document.documentElement) markReady();
  else document.addEventListener("DOMContentLoaded", markReady, { once: true });

  const SLOT_CLASS = "biliindex-slot";
  const BAR_CLASS = "biliindex-bar";
  let lastFireAt = 0;

  function findInComposedPath(e, className) {
    const path = typeof e.composedPath === "function" ? e.composedPath() : [];
    for (const n of path) {
      if (n instanceof Element && n.classList.contains(className)) return n;
    }
    return null;
  }

  function onPointerActivate(e) {
    if (e.button !== 0) return;
    const slot = findInComposedPath(e, SLOT_CLASS);
    if (!slot) return;
    let bar = findInComposedPath(e, BAR_CLASS);
    if (!bar) {
      const root = slot.getRootNode?.();
      if (root instanceof ShadowRoot && root.host instanceof Element) {
        bar = root.host.querySelector?.(`.${BAR_CLASS}`);
      }
      bar = bar || slot.closest?.(`.${BAR_CLASS}`);
    }
    if (!bar) return;

    const now = Date.now();
    if (now - lastFireAt < 280) return;
    lastFireAt = now;

    e.stopPropagation();
    e.stopImmediatePropagation();

    window.dispatchEvent(
      new CustomEvent("biliindex:slot-pointerdown", {
        bubbles: false,
        cancelable: true,
        detail: {
          bar,
          slot,
          upMid: bar.dataset?.upMid || "",
          slotName: slot.dataset?.slot || "",
        },
      })
    );
  }

  for (const type of ["pointerdown", "mousedown"]) {
    window.addEventListener(type, onPointerActivate, true);
  }
})();
