import { bound01 } from './helper.mjs';

/**
 * Converts an RGB color value to HSV
 * *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1].
 * *Returns:* { h, s, v } in [0,1]
 * @example
 * ```ts
 * rgb2hsv(0, 0, 0);
 * // { h: 0, s: 0, v: 0 }
 *
 * rgb2hsv(255, 255, 255);
 * // { h: 0, s: 0, v: 100 }
 *
 * rgb2hsv(217, 236, 188);
 * // { h: 83.75, s: 20.34, v: 92.55 }
 * ```
 */
function rgb2hsv(r, g, b) {
  r = bound01(r, 255);
  g = bound01(g, 255);
  b = bound01(b, 255);
  var max = Math.max(r, g, b);
  var min = Math.min(r, g, b);
  var h = 0;
  var v = max;
  var d = max - min;
  var s = max === 0 ? 0 : d / max;
  if (max === min) {
    h = 0; // achromatic
  } else {
    switch (max) {
      case r:
        h = (g - b) / d + (g < b ? 6 : 0);
        break;
      case g:
        h = (b - r) / d + 2;
        break;
      case b:
        h = (r - g) / d + 4;
        break;
    }
    h /= 6;
  }
  return {
    h: h * 360,
    s: s * 100,
    v: v * 100
  };
}
/**
 * Converts an HSV color value to RGB.
 * *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100].
 * *Returns:* { r, g, b } in the set [0, 255]
 * @example
 * ```ts
 * hsv2rgb(0, 0, 0);
 * // { r: 0, g: 0, b: 0 }
 *
 * hsv2rgb(0, 0, 100);
 * // { r: 255, g: 255, b: 255 }
 *
 * hsv2rgb(83.75, 20.34, 92.55);
 * // { r: 217, g: 236, b: 188 }
 * ```
 */
function hsv2rgb(h, s, v) {
  h = bound01(h, 360) * 6;
  s = bound01(s, 100);
  v = bound01(v, 100);
  var i = Math.floor(h);
  var f = h - i;
  var p = v * (1 - s);
  var q = v * (1 - f * s);
  var t = v * (1 - (1 - f) * s);
  var mod = i % 6;
  var r = [v, q, p, p, t, v][mod];
  var g = [t, v, v, q, p, p][mod];
  var b = [p, p, t, v, v, q][mod];
  return {
    r: Math.round(r * 255),
    g: Math.round(g * 255),
    b: Math.round(b * 255)
  };
}
var hsl2hsv = function hsl2hsv(hue, sat, light) {
  sat = sat / 100;
  light = light / 100;
  var smin = sat;
  var lmin = Math.max(light, 0.01);
  light *= 2;
  sat *= light <= 1 ? light : 2 - light;
  smin *= lmin <= 1 ? lmin : 2 - lmin;
  var v = (light + sat) / 2;
  var sv = light === 0 ? 2 * smin / (lmin + smin) : 2 * sat / (light + sat);
  return {
    h: hue,
    s: sv * 100,
    v: v * 100
  };
};
var hsv2hsl = function hsv2hsl(hue, sat, val) {
  return [hue, sat * val / ((hue = (2 - sat) * val) < 1 ? hue : 2 - hue) || 0, hue / 2];
};

export { hsl2hsv, hsv2hsl, hsv2rgb, rgb2hsv };
