export function splitCssDeclarations(style) {
  const declarations = [];
  let current = "";
  let parenDepth = 0;
  let inSingleQuote = false;
  let inDoubleQuote = false;
  for (let i = 0; i < style.length; i++) {
    const char = style[i];
    if (char === "'" && !inDoubleQuote) {
      inSingleQuote = !inSingleQuote;
    } else if (char === '"' && !inSingleQuote) {
      inDoubleQuote = !inDoubleQuote;
    } else if (!inSingleQuote && !inDoubleQuote) {
      if (char === "(") {
        parenDepth++;
      } else if (char === ")") {
        parenDepth = Math.max(0, parenDepth - 1);
      } else if (char === ";" && parenDepth === 0) {
        if (current.trim())
          declarations.push(current);
        current = "";
        continue;
      }
    }
    current += char;
  }
  if (current.trim())
    declarations.push(current);
  return declarations;
}
export const GRADIENT_COLOR_SPACE_RE = /\s+in\s+(?:oklab|oklch|srgb(?:-linear)?|display-p3|a98-rgb|prophoto-rgb|rec2020|xyz(?:-d(?:50|65))?|hsl|hwb|lab|lch)/g;
export function stripGradientColorSpace(value) {
  if (typeof value !== "string")
    return value;
  return value.replace(GRADIENT_COLOR_SPACE_RE, "");
}
const COLOR_MIX_HEX_RE = /color-mix\(in\s+\w+,\s*#([0-9a-fA-F]{3,8})\s+([\d.]+%?)\s*,\s*transparent\s*\)/g;
const COLOR_MIX_RGBA_RE = /color-mix\(in\s+\w+,\s*rgba?\((\d+)[\x09-\x0D\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*(?: |(?: \s*)?,)\s*(\d+)[\x09-\x0D\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*(?: |(?: \s*)?,)\s*(\d+)(?:\s*[/,]\s*[\d.]+)?\)\s+([\d.]+%?)\s*,\s*transparent\s*\)/g;
function hexToRgb(hex) {
  if (hex.length === 3)
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  if (hex.length !== 6 && hex.length !== 8)
    return null;
  const r = Number.parseInt(hex.slice(0, 2), 16);
  const g = Number.parseInt(hex.slice(2, 4), 16);
  const b = Number.parseInt(hex.slice(4, 6), 16);
  if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b))
    return null;
  return [r, g, b];
}
function parseColorMixAmount(amount) {
  let opacity = Number.parseFloat(amount);
  if (Number.isNaN(opacity))
    return Number.NaN;
  if (amount.endsWith("%"))
    opacity /= 100;
  else if (opacity > 1)
    opacity /= 100;
  return opacity;
}
export function resolveColorMix(value) {
  if (!value.includes("color-mix("))
    return value;
  let result = value.replace(COLOR_MIX_HEX_RE, (_match, hex, amount) => {
    const rgb = hexToRgb(hex);
    if (!rgb)
      return _match;
    const opacity = parseColorMixAmount(amount);
    if (Number.isNaN(opacity))
      return _match;
    return `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${opacity})`;
  });
  result = result.replace(COLOR_MIX_RGBA_RE, (_match, r, g, b, amount) => {
    const opacity = parseColorMixAmount(amount);
    if (Number.isNaN(opacity))
      return _match;
    return `rgba(${r}, ${g}, ${b}, ${opacity})`;
  });
  return result;
}
