import y from "./canUseDom.mjs";
import E from "./contains.mjs";
var g = "data-rc-order", s = "data-rc-priority", P = "rc-util-key", l = /* @__PURE__ */ new Map();
function p() {
  var e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, r = e.mark;
  return r ? r.startsWith("data-") ? r : "data-".concat(r) : P;
}
function c(e) {
  if (e.attachTo)
    return e.attachTo;
  var r = document.querySelector("head");
  return r || document.body;
}
function R(e) {
  return e === "queue" ? "prependQueue" : e ? "prepend" : "append";
}
function h(e) {
  return Array.from((l.get(e) || e).children).filter(function(r) {
    return r.tagName === "STYLE";
  });
}
function C(e) {
  var r = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  if (!y())
    return null;
  var n = r.csp, i = r.prepend, a = r.priority, u = a === void 0 ? 0 : a, o = R(i), d = o === "prependQueue", t = document.createElement("style");
  t.setAttribute(g, o), d && u && t.setAttribute(s, "".concat(u)), n != null && n.nonce && (t.nonce = n == null ? void 0 : n.nonce), t.innerHTML = e;
  var f = c(r), N = f.firstChild;
  if (i) {
    if (d) {
      var v = h(f).filter(function(m) {
        if (!["prepend", "prependQueue"].includes(m.getAttribute(g)))
          return !1;
        var b = Number(m.getAttribute(s) || 0);
        return u >= b;
      });
      if (v.length)
        return f.insertBefore(t, v[v.length - 1].nextSibling), t;
    }
    f.insertBefore(t, N);
  } else
    f.appendChild(t);
  return t;
}
function A(e) {
  var r = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, n = c(r);
  return h(n).find(function(i) {
    return i.getAttribute(p(r)) === e;
  });
}
function D(e) {
  var r = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, n = A(e, r);
  if (n) {
    var i = c(r);
    i.removeChild(n);
  }
}
function S(e, r) {
  var n = l.get(e);
  if (!n || !E(document, n)) {
    var i = C("", r), a = i.parentNode;
    l.set(e, a), e.removeChild(i);
  }
}
function L(e, r) {
  var n = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, i = c(n);
  S(i, n);
  var a = A(r, n);
  if (a) {
    var u, o;
    if ((u = n.csp) !== null && u !== void 0 && u.nonce && a.nonce !== ((o = n.csp) === null || o === void 0 ? void 0 : o.nonce)) {
      var d;
      a.nonce = (d = n.csp) === null || d === void 0 ? void 0 : d.nonce;
    }
    return a.innerHTML !== e && (a.innerHTML = e), a;
  }
  var t = C(e, n);
  return t.setAttribute(p(n), r), t;
}
export {
  C as injectCSS,
  D as removeCSS,
  L as updateCSS
};
