@use "../../variables/colors.scss" as colors;
@use "sass:math";
@use "sass:color";

// CONTRAST COLOR FUNCTIONS
// ========================
// Source: https://epiph.yt/en/blog/2023/fix-your-scss-color-contrast-function/

// DE-GAMMA AND RE-GAMMA
@function de-gamma($n) {
  @if $n <= 0.03928 {
    @return math.div($n, 12.92);
  } @else {
    @return math.pow((math.div(($n + 0.055), 1.055)), 2.4);
  }
}

@function re-gamma($n) {
  @if $n <= 0.0031308 {
    @return $n * 12.92;
  } @else {
    @return 1.055 * math.pow($n, math.div(1, 2.4)) - 0.055;
  }
}

// sRGB BT-709 BRIGHTNESS
@function brightness($c) {
  $rlin: de-gamma(math.div(color.channel($c, "red", $space: rgb), 255));
  $glin: de-gamma(math.div(color.channel($c, "green", $space: rgb), 255));
  $blin: de-gamma(math.div(color.channel($c, "blue", $space: rgb), 255));
  @return re-gamma(0.2126 * $rlin + 0.7152 * $glin + 0.0722 * $blin) * 100;
}

@function apply($color, $dark: colors.$contrast-dark, $light: colors.$contrast-light) {
  @if not $color {
    @return null;
  }

  $color-brightness: brightness($color);
  $light-text-brightness: brightness($light);
  $dark-text-brightness: brightness($dark);

  $light-diff: math.abs($color-brightness - $light-text-brightness);
  $dark-diff: math.abs($color-brightness - $dark-text-brightness);

  @if $light-diff > $dark-diff {
    @return $light;
  }

  @return $dark;
}

// Returns `true` if the given color is pure white.
// Checks the lightness channel in HSL color space.

// @param {Color} $color - The color to evaluate.
// @return {Boolean} Whether the color is pure white.
@function is-white($color) {
  @return color.channel($color, "lightness", $space: hsl) == 100%;
}
