@use "sass:color";
@use "sass:list";
@use "sass:math";

@function ch-color-luminance($color) {
  // Adapted from: https://github.com/LeaVerou/contrast-ratio/blob/gh-pages/color.js
  // Formula: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  $rgba: color.red($color), color.green($color), color.blue($color);
  $rgba2: ();

  @for $i from 1 through 3 {
    $rgb: list.nth($rgba, $i);
    $rgb: math.div($rgb, 255);

    //$rgb: if($rgb < .03928, math.div($rgb, 12.92), math.pow(math.div($rgb + .055, 1.055), 2.4,));
    @if $rgb < .03928 {
      $rgb: math.div($rgb, 12.92)
    } @else {
      $rgb: math.pow(math.div($rgb + .055, 1.055), 2.4);
    }


    $rgba2: list.append($rgba2, $rgb);
  }

  @return .2126 * list.nth($rgba2, 1) + .7152 * list.nth($rgba2, 2) + 0.0722 * list.nth($rgba2, 3);
}

@function ch-color-contrast($color1, $color2) {
  // Adapted from: https://github.com/LeaVerou/contrast-ratio/blob/gh-pages/color.js
  // Formula: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
  $luminance1: ch-color-luminance($color1) + .05;
  $luminance2: ch-color-luminance($color2) + .05;
  $ratio: math.div($luminance1, $luminance2);

  @if $luminance2 > $luminance1 {
    $ratio: math.div(1, $ratio);
  }

  $ratio: math.div(math.round($ratio * 10), 10);

  @return $ratio;
}

@function ch-best-color-contrast($base, $colors: (#fff, #000), $tolerance: 0) {
  $best: list.nth($colors, 1);
  $contrast: ch-color-contrast($base, $best);

  @for $i from 2 through list.length($colors) {
    $currentColor: list.nth($colors, $i);
    $currentContrast: ch-color-contrast($base, $currentColor);
    @if ($currentContrast - $contrast > $tolerance) {
      $best: $currentColor;
      $contrast: $currentContrast;
    }
  }

  @if ($contrast < 3) {
    @warn "Contrast ratio of #{$best} on #{$base} is pretty bad, just #{$contrast}";
  }

  @return $best;
}
