/**
 * Utility functions for mixing glaze colors
 */

/**
 * Convert hex color to RGB
 */
function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : null;
}

/**
 * Convert RGB to hex color
 */
function rgbToHex(r: number, g: number, b: number): string {
  const toHex = (n: number) => {
    const hex = Math.round(n).toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  };
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}

/**
 * Mix multiple hex colors together (average RGB values)
 * @param colors Array of hex color strings (e.g. ['#FF0000', '#0000FF'])
 * @returns Mixed hex color string
 */
export function mixColors(colors: string[]): string {
  if (colors.length === 0) {
    return '#808080'; // Default gray
  }

  if (colors.length === 1) {
    return colors[0];
  }

  // Convert all colors to RGB
  const rgbColors = colors.map(hexToRgb).filter((rgb) => rgb !== null) as {
    r: number;
    g: number;
    b: number;
  }[];

  if (rgbColors.length === 0) {
    return '#808080'; // Default gray
  }

  // Calculate average RGB values
  const avgR = rgbColors.reduce((sum, rgb) => sum + rgb.r, 0) / rgbColors.length;
  const avgG = rgbColors.reduce((sum, rgb) => sum + rgb.g, 0) / rgbColors.length;
  const avgB = rgbColors.reduce((sum, rgb) => sum + rgb.b, 0) / rgbColors.length;

  // Convert back to hex
  return rgbToHex(avgR, avgG, avgB);
}

/**
 * Mix two colors with custom ratios
 * @param color1 First hex color
 * @param color2 Second hex color
 * @param ratio1 Weight of first color (0-1), ratio2 will be (1 - ratio1)
 * @returns Mixed hex color string
 */
export function mixColorsWithRatio(color1: string, color2: string, ratio1: number): string {
  const rgb1 = hexToRgb(color1);
  const rgb2 = hexToRgb(color2);

  if (!rgb1 || !rgb2) {
    return '#808080';
  }

  const ratio2 = 1 - ratio1;

  const r = rgb1.r * ratio1 + rgb2.r * ratio2;
  const g = rgb1.g * ratio1 + rgb2.g * ratio2;
  const b = rgb1.b * ratio1 + rgb2.b * ratio2;

  return rgbToHex(r, g, b);
}

/**
 * Generate a name for a mixed glaze
 * @param glazeNames Array of glaze names that were mixed
 * @returns Generated name like "Blue + Yellow Mix"
 */
export function generateMixName(glazeNames: string[]): string {
  if (glazeNames.length === 0) {
    return 'Custom Mix';
  }

  if (glazeNames.length === 1) {
    return glazeNames[0];
  }

  if (glazeNames.length === 2) {
    return `${glazeNames[0]} + ${glazeNames[1]} Mix`;
  }

  // For 3+ glazes, show first two and count
  return `${glazeNames[0]} + ${glazeNames[1]} + ${glazeNames.length - 2} more`;
}
