// learn more https://en.wikipedia.org/wiki/HSL_and_HSV
// Ported from http://ariya.blogspot.com/2008/07/converting-between-hsl-and-hsv.html
@use "sass:math";
@use "sass:color";
@use "sass:list";
@use "sass:meta";

@function hsl-to-hsb($h, $ss: 0, $ll: 0) {
  @if meta.type_of($h) == 'list' {
    $ll: list.nth($h, 3);
    $ss: list.nth($h, 2);
    $h: list.nth($h, 1);
  } @else if meta.type_of($h) == 'color' {
    $ll: color.lightness($h);
    $ss: color.saturation($h);
    $h: color.hue($h);
  }

  @if math.unit($h) == 'deg' {
    $h: 3.1415 * 2 * math.div($h, 360deg);
  }
  @if math.unit($ss) == '%' {
    $ss: 0 + math.div($ss, 100%);
  }
  @if math.unit($ll) == '%' {
    $ll: 0 + math.div($ll, 100%);
  }

  $ll: $ll * 2;

  @if $ll <= 1 {
    $ss: $ss * $ll;
  } @else {
    $ss: $ss * (2 - $ll);
  }

  $v: math.div($ll + $ss, 2);

  $s: 0;
  @if $ll + $ss != 0 {
    $s: math.div(2 * $ss, $ll + $ss);
  }

  $hsb-h: math.div(360deg * $h, 3.1415 * 2);
  $hsb-s: math.percentage(math.max(0, math.min(1, $s)));
  $hsb-b: math.percentage(math.max(0, math.min(1, $v)));

  @return $hsb-h, $hsb-s, $hsb-b;
}

@function hsb-to-hsl($h, $s: 0, $v: 0) {
  @if meta.type_of($h) == 'list' {
    $v: list.nth($h, 3);
    $s: list.nth($h, 2);
    $h: list.nth($h, 1);
  }

  @if math.unit($h) == 'deg' {
    $h: 3.1415 * 2 * math.div($h, 360deg);
  }
  @if math.unit($s) == '%' {
    $s: 0 + math.div($s, 100%);
  }
  @if math.unit($v) == '%' {
    $v: 0 + math.div($v, 100%);
  }

  $ss: $s * $v;
  $ll: (2 - $s) * $v;

  @if ($ll == 2 or $ll == 0) {
    $ss: 0;
  } @else if $ll <= 1 {
    $ss: math.div($ss, $ll);
  } @else {
    $ss: math.div($ss, 2 - $ll);
  }

  $ll: math.div($ll, 2);

  $hsl-h: math.div(360deg * $h, 3.1415 * 2);
  $hsl-s: math.percentage(math.max(0, math.min(1, $ss)));
  $hsl-l: math.percentage(math.max(0, math.min(1, $ll)));

  @return hsl($hsl-h, $hsl-s, $hsl-l);
}
