import hash from '@emotion/hash';
import { computed, ref } from 'vue';
import { ATTR_TOKEN, CSS_IN_JS_INSTANCE, CSS_IN_JS_INSTANCE_ID } from '../StyleContext.mjs';
import { flattenToken, token2key } from '../util.mjs';
import useClientCache from './useGlobalCache.mjs';

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[${ATTR_TOKEN}="${key}"]`);
    styles.forEach((style) => {
      var _a;
      if (style[CSS_IN_JS_INSTANCE] === 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 = ref({})) {
  const mergedToken = computed(() => Object.assign({}, ...tokens.value));
  const tokenStr = computed(() => flattenToken(mergedToken.value));
  const overrideTokenStr = computed(() => flattenToken(option.value.override || EMPTY_OVERRIDE));
  const cachedToken = useClientCache(
    "token",
    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 = 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;
}

export { useCacheToken as default };
//# sourceMappingURL=useCacheToken.mjs.map
