@use "sass:color";
@use "sass:map";
@use "sass:math";
@use "sass:meta";

//  Type-casting
// --------------------------------------------------------

// Get a unit-less numeric value
@function num($value) {
  @if meta.type-of($value) != number {
    @error 'Could not convert `#{$value}` - must be `type-of number`';
    @return null;
  }
  @if math.unit($value) == "%" {
    @return math.div($value, 100%);
  }
  @return math.div($value, $value * 0 + 1);
}

//  Color
// --------------------------------------------------------

// Increases perceptual color lightness.
@function lighten($color, $percent) {
  $scaled: hsl(
    color.channel($color, "hue", $space: hsl),
    color.channel($color, "saturation", $space: hsl),
    color.channel($color, "lightness", $space: hsl) * (1 + num($percent))
  );
  $mixed: color.mix(hsl(0, 0%, 100%), $color, 100% * num($percent));
  @return color.mix($scaled, $mixed, 75%);
}

// Returns the NTSC luminance of `$color` as a float (between 0 and 1).
// 1 is pure white, 0 is pure black.
@function luminance($color) {
  $colors: (
    "red": color.channel($color, "red", $space: rgb),
    "green": color.channel($color, "green", $space: rgb),
    "blue": color.channel($color, "blue", $space: rgb),
  );

  @each $name, $value in $colors {
    $adjusted: 0;
    $value: math.div($value, 255);
    @if $value < 0.03928 {
      $value: math.div($value, 12.92);
    } @else {
      $value: math.div($value + 0.055, 1.055);
      $value: math.pow($value, 2.4);
    }

    $colors: map.merge(
      $colors,
      (
        $name: $value,
      )
    );
  }

  @return (map.get($colors, "red") * 0.2126) +
    (map.get($colors, "green") * 0.7152) + (map.get($colors, "blue") * 0.0722);
}

// Blends an RGBA color with a static background color based on its
// alpha channel. Returns an RGB color, which is compatible with IE8.
@function fake-alpha($color-rgba, $color-background) {
  @return color.mix(
    color.change($color-rgba, $alpha: 1),
    $color-background,
    color.alpha($color-rgba) * 100%
  );
}
