/**
 * Color derivation utilities for Schedule-X lightColors.
 *
 * Derives container (15% opacity over white) and onContainer (darkened 40%)
 * from a member's hex color. No third-party color library — the math is simple.
 *
 * UI-SPEC §"Color derivation rule for event chips":
 *   container  = MAIN at 15% opacity blended over #FFFFFF
 *   onContainer = MAIN darkened 40%
 */

/**
 * Parse a 6-digit hex color string to [r, g, b] in 0–255 range.
 */
function hexToRgb(hex: string): [number, number, number] {
  const clean = hex.replace('#', '');
  const r = parseInt(clean.slice(0, 2), 16);
  const g = parseInt(clean.slice(2, 4), 16);
  const b = parseInt(clean.slice(4, 6), 16);
  return [r, g, b];
}

/**
 * Convert [r, g, b] (0–255) to a #RRGGBB hex string.
 */
function rgbToHex(r: number, g: number, b: number): string {
  return '#' + [r, g, b].map((v) => Math.round(v).toString(16).padStart(2, '0')).join('');
}

/**
 * Blend a foreground color at `alpha` opacity over a white (#FFFFFF) background.
 * Returns the resulting opaque hex color.
 *
 * Formula (standard alpha compositing over white):
 *   result = fg * alpha + 255 * (1 - alpha)
 */
export function hexToContainer(hex: string): string {
  const [r, g, b] = hexToRgb(hex);
  const alpha = 0.15;
  const blendChannel = (fg: number) => fg * alpha + 255 * (1 - alpha);
  return rgbToHex(blendChannel(r), blendChannel(g), blendChannel(b));
}

/**
 * Darken a hex color by the given factor (0–1).
 * A factor of 0.4 means "40% darker" — each channel is multiplied by (1 - factor).
 */
export function hexToOnContainer(hex: string): string {
  const [r, g, b] = hexToRgb(hex);
  const factor = 1 - 0.4; // darken 40%
  return rgbToHex(r * factor, g * factor, b * factor);
}

/**
 * Derive all three Schedule-X lightColors values from a single member hex.
 *
 * Returns:
 *   main        — the original hex
 *   container   — main at 15% opacity blended over white (event chip background)
 *   onContainer — main darkened 40% (event chip text, passed to Schedule-X)
 */
export function deriveScheduleXColors(main: string): {
  main: string;
  container: string;
  onContainer: string;
} {
  return {
    main,
    container: hexToContainer(main),
    onContainer: hexToOnContainer(main),
  };
}
