import hash from '@emotion/hash';
import unitless from '@emotion/unitless';
import { serialize, compile, stringify } from 'stylis';
import { computed } from 'vue';
import canUseDom from '../../_util/canUseDom.mjs';
import '../linters/index.mjs';
import { useStyleInject, ATTR_MARK, CSS_IN_JS_INSTANCE, CSS_IN_JS_INSTANCE_ID, ATTR_TOKEN, ATTR_DEV_CACHE_PATH } from '../StyleContext.mjs';
import { supportLayer } from '../util.mjs';
import { updateCSS, removeCSS } from '../../vc-util/Dom/dynamicCSS.mjs';
import useClientCache from './useGlobalCache.mjs';
import linter from '../linters/contentQuotesLinter.mjs';
import linter$1 from '../linters/hashedAnimationLinter.mjs';

const isClientSide = canUseDom();
const SKIP_CHECK = "_skip_check_";
function normalizeStyle(styleStr) {
  const serialized = serialize(compile(styleStr), stringify);
  return serialized.replace(/\{%%%\:[^;];}/g, ";");
}
function isCompoundCSSProperty(value) {
  return typeof value === "object" && value && SKIP_CHECK in value;
}
function injectSelectorHash(key, hashId, hashPriority) {
  if (!hashId)
    return key;
  const hashClassName = `.${hashId}`;
  const hashSelector = hashPriority === "low" ? `:where(${hashClassName})` : hashClassName;
  const keys = key.split(",").map((k) => {
    var _a;
    const fullPath = k.trim().split(/\s+/);
    let firstPath = fullPath[0] || "";
    const htmlElement = ((_a = firstPath.match(/^\w+/)) == null ? void 0 : _a[0]) || "";
    firstPath = `${htmlElement}${hashSelector}${firstPath.slice(htmlElement.length)}`;
    return [firstPath, ...fullPath.slice(1)].join(" ");
  });
  return keys.join(",");
}
const globalEffectStyleKeys = /* @__PURE__ */ new Set();
const _cf = process.env.NODE_ENV !== "production" ? () => globalEffectStyleKeys.clear() : void 0;
const parseStyle = (interpolation, config = {}, { root, injectHash, parentSelectors } = {
  root: true,
  parentSelectors: []
}) => {
  const { hashId, layer, path, hashPriority, transformers = [], linters = [] } = config;
  let styleStr = "";
  let effectStyle = {};
  function parseKeyframes(keyframes) {
    const animationName = keyframes.getName(hashId);
    if (!effectStyle[animationName]) {
      const [parsedStr] = parseStyle(keyframes.style, config, {
        root: false,
        parentSelectors
      });
      effectStyle[animationName] = `@keyframes ${keyframes.getName(hashId)}${parsedStr}`;
    }
  }
  function flattenList(list, fullList = []) {
    list.forEach((item) => {
      if (Array.isArray(item))
        flattenList(item, fullList);
      else if (item)
        fullList.push(item);
    });
    return fullList;
  }
  const flattenStyleList = flattenList(
    Array.isArray(interpolation) ? interpolation : [interpolation]
  );
  flattenStyleList.forEach((originStyle) => {
    const style = typeof originStyle === "string" && !root ? {} : originStyle;
    if (typeof style === "string") {
      styleStr += `${style}
`;
    } else if (style._keyframe) {
      parseKeyframes(style);
    } else {
      const mergedStyle = transformers.reduce((prev, trans) => {
        var _a;
        return ((_a = trans == null ? void 0 : trans.visit) == null ? void 0 : _a.call(trans, prev)) || prev;
      }, style);
      Object.keys(mergedStyle).forEach((key) => {
        var _a;
        const value = mergedStyle[key];
        if (typeof value === "object" && value && (key !== "animationName" || !value._keyframe) && !isCompoundCSSProperty(value)) {
          let subInjectHash = false;
          let mergedKey = key.trim();
          let nextRoot = false;
          if ((root || injectHash) && hashId) {
            if (mergedKey.startsWith("@")) {
              subInjectHash = true;
            } else {
              mergedKey = injectSelectorHash(key, hashId, hashPriority);
            }
          } else if (root && !hashId && (mergedKey === "&" || mergedKey === "")) {
            mergedKey = "";
            nextRoot = true;
          }
          const [parsedStr, childEffectStyle] = parseStyle(value, config, {
            root: nextRoot,
            injectHash: subInjectHash,
            parentSelectors: [...parentSelectors, mergedKey]
          });
          effectStyle = {
            ...effectStyle,
            ...childEffectStyle
          };
          styleStr += `${mergedKey}${parsedStr}`;
        } else {
          const actualValue = (_a = value == null ? void 0 : value.value) != null ? _a : value;
          if (process.env.NODE_ENV !== "production" && (typeof value !== "object" || !(value == null ? void 0 : value[SKIP_CHECK]))) {
            [linter, linter$1, ...linters].forEach(
              (linter) => linter(key, actualValue, { path, hashId, parentSelectors })
            );
          }
          const styleName = key.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
          let formatValue = actualValue;
          if (!unitless[key] && typeof formatValue === "number" && formatValue !== 0)
            formatValue = `${formatValue}px`;
          if (key === "animationName" && (value == null ? void 0 : value._keyframe)) {
            parseKeyframes(value);
            formatValue = value.getName(hashId);
          }
          styleStr += `${styleName}:${formatValue};`;
        }
      });
    }
  });
  if (!root) {
    styleStr = `{${styleStr}}`;
  } else if (layer && supportLayer()) {
    const layerCells = layer.split(",");
    const layerName = layerCells[layerCells.length - 1].trim();
    styleStr = `@layer ${layerName} {${styleStr}}`;
    if (layerCells.length > 1) {
      styleStr = `@layer ${layer}{%%%:%}${styleStr}`;
    }
  }
  return [styleStr, effectStyle];
};
function uniqueHash(path, styleStr) {
  return hash(`${path.join("%")}${styleStr}`);
}
function useStyleRegister(info, styleFn) {
  const styleContext = useStyleInject();
  const tokenKey = computed(() => info.value.token._tokenKey);
  const fullPath = computed(() => [tokenKey.value, ...info.value.path]);
  let isMergedClientSide = isClientSide;
  if (process.env.NODE_ENV !== "production" && styleContext.value.mock !== void 0)
    isMergedClientSide = styleContext.value.mock === "client";
  useClientCache(
    "style",
    fullPath,
    // Create cache if needed
    () => {
      const styleObj = styleFn();
      const { hashPriority, container, transformers, linters } = styleContext.value;
      const { path, hashId, layer } = info.value;
      const [parsedStyle, effectStyle] = parseStyle(styleObj, {
        hashId,
        hashPriority,
        layer,
        path: path.join("-"),
        transformers,
        linters
      });
      const styleStr = normalizeStyle(parsedStyle);
      const styleId = uniqueHash(fullPath.value, styleStr);
      if (isMergedClientSide) {
        const style = updateCSS(styleStr, styleId, {
          mark: ATTR_MARK,
          prepend: "queue",
          attachTo: container
        });
        style[CSS_IN_JS_INSTANCE] = CSS_IN_JS_INSTANCE_ID;
        style.setAttribute(ATTR_TOKEN, tokenKey.value);
        if (process.env.NODE_ENV !== "production")
          style.setAttribute(ATTR_DEV_CACHE_PATH, fullPath.value.join("|"));
        Object.keys(effectStyle).forEach((effectKey) => {
          if (!globalEffectStyleKeys.has(effectKey)) {
            globalEffectStyleKeys.add(effectKey);
            updateCSS(normalizeStyle(effectStyle[effectKey]), `_effect-${effectKey}`, {
              mark: ATTR_MARK,
              prepend: "queue",
              attachTo: container
            });
          }
        });
      }
      return [styleStr, tokenKey.value, styleId];
    },
    // Remove cache if no need
    ([, , styleId], fromHMR) => {
      if ((fromHMR || styleContext.value.autoClear) && isClientSide)
        removeCSS(styleId, { mark: ATTR_MARK });
    }
  );
  return (node) => {
    return node;
  };
}
function extractStyle(cache) {
  const styleKeys = Array.from(cache.cache.keys()).filter((key) => key.startsWith("style%"));
  let styleText = "";
  styleKeys.forEach((key) => {
    const [styleStr, tokenKey, styleId] = cache.cache.get(key)[1];
    styleText += `<style ${ATTR_TOKEN}="${tokenKey}" ${ATTR_MARK}="${styleId}">${styleStr}</style>`;
  });
  return styleText;
}

export { _cf, useStyleRegister as default, extractStyle, normalizeStyle, parseStyle };
//# sourceMappingURL=useStyleRegister.mjs.map
