import { render } from "./render.mjs";
import { removeElement, queryElement, createElement } from "./utils.mjs";
import murmur2 from "../../../../@emotion_hash@0.8.0/node_modules/@emotion/hash/dist/hash.browser.esm.mjs";
if (typeof window !== "undefined") {
  window.__cssrContext = {};
}
function unmount(intance, node, id) {
  const { els } = node;
  if (id === void 0) {
    els.forEach(removeElement);
    node.els = [];
  } else {
    const target = queryElement(id);
    if (target && els.includes(target)) {
      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(node, instance, props, silent);
    }
    return;
  }
  let style;
  if (id === void 0) {
    style = node.render(props);
    id = murmur2(style);
  }
  if (ssrAdapter) {
    ssrAdapter.adapter(id, style !== null && style !== void 0 ? style : node.render(props));
    return;
  }
  const queriedTarget = queryElement(id);
  if (queriedTarget !== null && !force) {
    return queriedTarget;
  }
  const target = queriedTarget !== null && queriedTarget !== void 0 ? queriedTarget : 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;
}
export {
  mount,
  unmount
};
