@use "sass:math";

@function split-color($color) {
  @return red($color) green($color) blue($color);
}

@function fg-color($color) {
  $contrast-black: contrast-ratio($color, #000000);
  $contrast-white: contrast-ratio($color, #ffffff);
  @return if($contrast-black > $contrast-white, #000000, #ffffff);
}

// Taken & adapted from https://github.com/twbs/bootstrap/blob/main/scss/_functions.scss
@function contrast-ratio($background, $foreground) {
  $l1: luminance($background);
  $l2: luminance(opaque($background, $foreground));

  @return if($l1 > $l2, math.div($l1 + 0.05, $l2 + 0.05), math.div($l2 + 0.05, $l1 + 0.05));
}

// Return WCAG2.0 relative luminance
// See https://www.w3.org/WAI/GL/wiki/Relative_luminance
// See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
@function luminance($color) {
  $rgb: (
    "r": red($color),
    "g": green($color),
    "b": blue($color),
  );

  @each $name, $value in $rgb {
    $value: if(
      math.div($value, 255) < 0.03928,
      math.div(math.div($value, 255), 12.92),
      math.pow(math.div((math.div($value, 255) + 0.055), 1.055), 2.4)
    );
    $rgb: map-merge(
      $rgb,
      (
        $name: $value,
      )
    );
  }

  @return (map-get($rgb, "r") * 0.2126) + (map-get($rgb, "g") * 0.7152) + (map-get($rgb, "b") * 0.0722);
}

@function opaque($background, $foreground) {
  @return mix(rgba($foreground, 1), $background, opacity($foreground) * 100%);
}
