"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const render = require("./render.js");
const utils = require("./utils.js");
const hash_browser_esm = require("../../../../@emotion_hash@0.8.0/node_modules/@emotion/hash/dist/hash.browser.esm.js");
if (typeof window !== "undefined") {
  window.__cssrContext = {};
}
function unmount(intance, node, id) {
  const { els } = node;
  if (id === void 0) {
    els.forEach(utils.removeElement);
    node.els = [];
  } else {
    const target = utils.queryElement(id);
    if (target && els.includes(target)) {
      utils.removeElement(target);
      node.els = els.filter((el) => el !== target);
    }
  }
}
function addElementToList(els, target) {
  els.push(target);
}
function mount(instance, node, id, props, head, silent, force, anchorMetaName, ssrAdapter) {
  if (silent && !ssrAdapter) {
    if (id === void 0) {
      console.error("[css-render/mount]: `id` is required in `silent` mode.");
      return;
    }
    const cssrContext = window.__cssrContext;
    if (!cssrContext[id]) {
      cssrContext[id] = true;
      render.render(node, instance, props, silent);
    }
    return;
  }
  let style;
  if (id === void 0) {
    style = node.render(props);
    id = hash_browser_esm.default(style);
  }
  if (ssrAdapter) {
    ssrAdapter.adapter(id, style !== null && style !== void 0 ? style : node.render(props));
    return;
  }
  const queriedTarget = utils.queryElement(id);
  if (queriedTarget !== null && !force) {
    return queriedTarget;
  }
  const target = queriedTarget !== null && queriedTarget !== void 0 ? queriedTarget : utils.createElement(id);
  if (style === void 0)
    style = node.render(props);
  target.textContent = style;
  if (queriedTarget !== null)
    return queriedTarget;
  if (anchorMetaName) {
    const anchorMetaEl = document.head.querySelector(`meta[name="${anchorMetaName}"]`);
    if (anchorMetaEl) {
      document.head.insertBefore(target, anchorMetaEl);
      addElementToList(node.els, target);
      return target;
    }
  }
  if (head) {
    document.head.insertBefore(target, document.head.querySelector("style, link"));
  } else {
    document.head.appendChild(target);
  }
  addElementToList(node.els, target);
  return target;
}
exports.mount = mount;
exports.unmount = unmount;
