import { ownerDocument } from "../dom/owner-document.jsx";
import { DISABLE_SCROLLBAR_STYLE } from "./style-disable-scrollbar.jsx";

/**
 * Per-document ref-counted disable-scrollbar style registration.
 *
 * Each `<ScrollArea.Root>` would otherwise inject its own `<style>` tag with
 * identical CSS — multiple roots on the page give you N copies of the same
 * rules. This helper installs a single `<style>` per document (keyed by the
 * element's owning document so shadow roots and iframe documents don't
 * cross-pollute with the main document) and increments a counter for every
 * mount; only the last unmount removes the tag.
 *
 * Shadow-DOM note: `ownerDocument` walks up to the owning `Document` (not
 * the shadow-root), so a style registered from inside a shadow tree still
 * lives in the owning document's `<head>`. This matches the rest of the
 * `internals/dom/` utilities.
 */

const ATTRIBUTE = "data-quoin-scroll-area-disable";
const registry = new WeakMap();
export function registerDisableScrollbarStyle(anchor, nonce) {
  const doc = ownerDocument(anchor);
  let entry = registry.get(doc);
  if (entry == null) {
    // Look for an existing tag injected by a prior registration that lost
    // its WeakMap entry (e.g. during HMR). Reuse it rather than stacking.
    const existing = doc.querySelector(`style[${ATTRIBUTE}]`);
    const element = existing ?? doc.createElement("style");
    if (existing == null) {
      element.setAttribute(ATTRIBUTE, "");
      if (nonce) element.setAttribute("nonce", nonce);
      element.textContent = DISABLE_SCROLLBAR_STYLE;
      doc.head.appendChild(element);
    }
    entry = {
      count: 0,
      element
    };
    registry.set(doc, entry);
  }
  entry.count += 1;
  return () => {
    const current = registry.get(doc);
    if (current == null) return;
    current.count -= 1;
    if (current.count <= 0) {
      current.element.remove();
      registry.delete(doc);
    }
  };
}
//# sourceMappingURL=register-disable-scrollbar-style.jsx.map
