// packages/style-engine/src/styles/utils.ts
import { paramCase as kebabCase } from "change-case";
import {
  VARIABLE_REFERENCE_PREFIX,
  VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE,
  VARIABLE_PATH_SEPARATOR_TOKEN_STYLE
} from "./constants.mjs";
var getStyleValueByPath = (object, path) => {
  let value = object;
  path.forEach((fieldName) => {
    value = value?.[fieldName];
  });
  return value;
};
function generateRule(style, options, path, ruleKey) {
  const styleValue = getStyleValueByPath(style, path);
  return styleValue ? [
    {
      selector: options?.selector,
      key: ruleKey,
      value: getCSSValueFromRawStyle(styleValue)
    }
  ] : [];
}
function generateBoxRules(style, options, path, ruleKeys, individualProperties = ["top", "right", "bottom", "left"]) {
  const boxStyle = getStyleValueByPath(
    style,
    path
  );
  if (!boxStyle) {
    return [];
  }
  const rules = [];
  if (typeof boxStyle === "string") {
    rules.push({
      selector: options?.selector,
      key: ruleKeys.default,
      value: getCSSValueFromRawStyle(boxStyle)
    });
  } else {
    const sideRules = individualProperties.reduce(
      (acc, side) => {
        const value = getCSSValueFromRawStyle(
          getStyleValueByPath(boxStyle, [side])
        );
        if (value) {
          acc.push({
            selector: options?.selector,
            key: ruleKeys?.individual.replace(
              "%s",
              upperFirst(side)
            ),
            value
          });
        }
        return acc;
      },
      []
    );
    rules.push(...sideRules);
  }
  return rules;
}
function getCSSValueFromRawStyle(styleValue) {
  if (typeof styleValue === "string" && styleValue.startsWith(VARIABLE_REFERENCE_PREFIX)) {
    const variable = styleValue.slice(VARIABLE_REFERENCE_PREFIX.length).split(VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE).map(
      (presetVariable) => kebabCase(presetVariable, {
        splitRegexp: [
          /([a-z0-9])([A-Z])/g,
          // fooBar => foo-bar, 3Bar => 3-bar
          /([0-9])([a-z])/g,
          // 3bar => 3-bar
          /([A-Za-z])([0-9])/g,
          // Foo3 => foo-3, foo3 => foo-3
          /([A-Z])([A-Z][a-z])/g
          // FOOBar => foo-bar
        ]
      })
    ).join(VARIABLE_PATH_SEPARATOR_TOKEN_STYLE);
    return `var(--wp--${variable})`;
  }
  return styleValue;
}
function upperFirst(string) {
  const [firstLetter, ...rest] = string;
  return firstLetter.toUpperCase() + rest.join("");
}
function camelCaseJoin(strings) {
  const [firstItem, ...rest] = strings;
  return firstItem.toLowerCase() + rest.map(upperFirst).join("");
}
function safeDecodeURI(uri) {
  try {
    return decodeURI(uri);
  } catch (uriError) {
    return uri;
  }
}
export {
  camelCaseJoin,
  generateBoxRules,
  generateRule,
  getCSSValueFromRawStyle,
  getStyleValueByPath,
  safeDecodeURI,
  upperFirst
};
//# sourceMappingURL=utils.mjs.map
