'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var hash = require('@emotion/hash');
var vue = require('vue');
var StyleContext = require('../StyleContext.js');
var util = require('../util.js');
var useGlobalCache = require('./useGlobalCache.js');

const EMPTY_OVERRIDE = {};
const hashPrefix = process.env.NODE_ENV !== "production" ? "css-dev-only-do-not-override" : "css";
const tokenKeys = /* @__PURE__ */ new Map();
function recordCleanToken(tokenKey) {
  tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) + 1);
}
function removeStyleTags(key) {
  if (typeof document !== "undefined") {
    const styles = document.querySelectorAll(`style[${StyleContext.ATTR_TOKEN}="${key}"]`);
    styles.forEach((style) => {
      var _a;
      if (style[StyleContext.CSS_IN_JS_INSTANCE] === StyleContext.CSS_IN_JS_INSTANCE_ID)
        (_a = style.parentNode) == null ? void 0 : _a.removeChild(style);
    });
  }
}
function cleanTokenStyle(tokenKey) {
  tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) - 1);
  const tokenKeyList = Array.from(tokenKeys.keys());
  const cleanableKeyList = tokenKeyList.filter((key) => {
    const count = tokenKeys.get(key) || 0;
    return count <= 0;
  });
  if (cleanableKeyList.length < tokenKeyList.length) {
    cleanableKeyList.forEach((key) => {
      removeStyleTags(key);
      tokenKeys.delete(key);
    });
  }
}
function useCacheToken(theme, tokens, option = vue.ref({})) {
  const mergedToken = vue.computed(() => Object.assign({}, ...tokens.value));
  const tokenStr = vue.computed(() => util.flattenToken(mergedToken.value));
  const overrideTokenStr = vue.computed(() => util.flattenToken(option.value.override || EMPTY_OVERRIDE));
  const cachedToken = useGlobalCache.default(
    "token",
    vue.computed(() => [
      option.value.salt || "",
      theme.value.id,
      tokenStr.value,
      overrideTokenStr.value
    ]),
    () => {
      const { salt = "", override = EMPTY_OVERRIDE, formatToken } = option.value;
      const derivativeToken = theme.value.getDerivativeToken(mergedToken.value);
      let mergedDerivativeToken = {
        ...derivativeToken,
        ...override
      };
      if (formatToken)
        mergedDerivativeToken = formatToken(mergedDerivativeToken);
      const tokenKey = util.token2key(mergedDerivativeToken, salt);
      mergedDerivativeToken._tokenKey = tokenKey;
      recordCleanToken(tokenKey);
      const hashId = `${hashPrefix}-${hash(tokenKey)}`;
      mergedDerivativeToken._hashId = hashId;
      return [mergedDerivativeToken, hashId];
    },
    (cache) => {
      cleanTokenStyle(cache[0]._tokenKey);
    }
  );
  return cachedToken;
}

exports.default = useCacheToken;
//# sourceMappingURL=useCacheToken.js.map
