import { useMemo } from "react";
import { useSyncExternalStore } from "use-sync-external-store/shim";
import { getResolvedPaletteColors } from "./../ricos-styles/themeStrategy/generators/palette.js";
import { resolveColorsPalette } from "./../wix-rich-content-common/index.js";
import { areGradientsEqual } from "./are-gradients-equal.js";
import { THEME_COLOR_SLOT_MAP } from "./theme-color-token.js";
const DEFAULT_PALETTE_SIZE = 58;
const COLORS_KEY = "ricos/custom-colors";
const GRADIENTS_KEY = "ricos/custom-gradients";
const getCustomColors = (colorManager, legacyGetColors) => colorManager?.colors ?? legacyGetColors?.() ?? readStorage(COLORS_KEY, []);
const isSameColor = (left, right) => left.toUpperCase() === right.toUpperCase();
const isNonBlank = (value) => typeof value === "string" && value.trim().length > 0;
const VISIBLE_SWATCH_TOKENS = Object.entries(THEME_COLOR_SLOT_MAP).slice(0, 6).map(([slot, field]) => [field, `$theme-color-${slot}`]);
const dedupeByHex = (swatches) => {
  const seen = /* @__PURE__ */ new Set();
  return swatches.filter((s) => {
    const key = s.hex.toUpperCase();
    if (seen.has(key)) {
      return false;
    }
    seen.add(key);
    return true;
  });
};
const getResolvedCustomColors = (colorManager, currentColor, legacyGetColors, paletteSize = DEFAULT_PALETTE_SIZE) => {
  return resolveColorsPalette(
    getCustomColors(colorManager, legacyGetColors),
    currentColor,
    paletteSize
  );
};
const resolveThemeColorsPalette = (theme, fallbackColors = []) => {
  const configSwatches = fallbackColors.filter(isNonBlank).map((hex) => ({ hex }));
  if (configSwatches.length > 0) {
    return dedupeByHex(configSwatches);
  }
  const { colorPalette } = theme;
  if (colorPalette) {
    const swatches = [];
    for (const [field, token] of VISIBLE_SWATCH_TOKENS) {
      const value = colorPalette[field];
      if (isNonBlank(value)) {
        swatches.push({
          hex: colorPalette.format === "rgbTuple" ? `rgb(${value})` : value,
          token
        });
      }
    }
    return dedupeByHex(swatches);
  }
  return dedupeByHex(
    Object.values(getResolvedPaletteColors(theme.palette)).filter(isNonBlank).map((hex) => ({ hex }))
  );
};
const useResolvedCustomColors = (colorManager, legacyGetColors, paletteSize = DEFAULT_PALETTE_SIZE) => {
  const storageVersion = useStorageVersion();
  return useMemo(() => {
    return getResolvedCustomColors(colorManager, void 0, legacyGetColors, paletteSize);
  }, [colorManager?.colors, legacyGetColors, paletteSize, storageVersion]);
};
const handleColorAdded = (color, colorManager, legacyOnColorAdded) => {
  if (colorManager) {
    colorManager.setColors([...colorManager.colors, color]);
  } else if (legacyOnColorAdded) {
    legacyOnColorAdded(color);
    notify();
  } else {
    writeStorage(COLORS_KEY, [...readStorage(COLORS_KEY, []), color]);
  }
};
const handleColorDeleted = (color, colorManager) => {
  if (colorManager) {
    colorManager.setColors(
      colorManager.colors.filter((savedColor) => !isSameColor(savedColor, color))
    );
  } else {
    writeStorage(
      COLORS_KEY,
      readStorage(COLORS_KEY, []).filter((savedColor) => !isSameColor(savedColor, color))
    );
  }
};
const useResolvedCustomGradients = (colorManager) => {
  const storageVersion = useStorageVersion();
  return useMemo(() => {
    return colorManager?.gradients ?? readStorage(GRADIENTS_KEY, []);
  }, [colorManager?.gradients, storageVersion]);
};
const handleGradientAdded = (gradient, colorManager) => {
  if (colorManager?.setGradients) {
    colorManager.setGradients([...colorManager.gradients ?? [], gradient]);
  } else {
    writeStorage(GRADIENTS_KEY, [...readStorage(GRADIENTS_KEY, []), gradient]);
  }
};
const handleGradientDeleted = (gradient, colorManager) => {
  if (colorManager?.setGradients) {
    colorManager.setGradients(
      (colorManager.gradients ?? []).filter(
        (savedGradient) => !areGradientsEqual(savedGradient, gradient)
      )
    );
  } else {
    writeStorage(
      GRADIENTS_KEY,
      readStorage(GRADIENTS_KEY, []).filter(
        (savedGradient) => !areGradientsEqual(savedGradient, gradient)
      )
    );
  }
};
let version = 0;
const listeners = /* @__PURE__ */ new Set();
const notify = () => {
  version++;
  listeners.forEach((listener) => listener());
};
const readStorage = (key, fallback) => {
  try {
    return JSON.parse(localStorage.getItem(key)) ?? fallback;
  } catch {
    return fallback;
  }
};
const writeStorage = (key, value) => {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {
  }
  notify();
};
const useStorageVersion = () => useSyncExternalStore(
  (listener) => {
    listeners.add(listener);
    return () => void listeners.delete(listener);
  },
  () => version
);
export {
  getResolvedCustomColors,
  handleColorAdded,
  handleColorDeleted,
  handleGradientAdded,
  handleGradientDeleted,
  resolveThemeColorsPalette,
  useResolvedCustomColors,
  useResolvedCustomGradients
};
//# sourceMappingURL=color-manager-utils.js.map
