@use 'sass:color';
@use 'sass:map';
@use 'sass:math';
@use 'setting' as *;
@use '../config' as *;

/// Get any color value from $colors (or any) Sass map.
/// @param {string} $key - The key name of the color.
/// @param {string} $type - The type of the color group (base, dark, etc.).
/// @param {boolean} $only-color - If true, return only the color value.
/// @param {map} $map - The map to get the color from.
/// @return {color} - The color value or the variable.
@function color(
  $key,
  $type: 'base',
  $only-color: false,
  $map: $colors
) {
  @if not map.has-key($map, $type, $key) {
    @error 'The #{$key} key name doesn\'t exist under #{$type} at the specified map (default: $colors).';
  }

  @if map.get($map, $type, $key) == null {
    @return null;
  }

  @if $only-color {
    @return map.get($map, $type, $key);
  }

  @if map.get($settings, color-fallback) {
    @return var(--#{$internal-prefix}#{$type}-color-#{$key}, #{map.get($map, $type, $key)});
  }

  @return var(--#{$internal-prefix}#{$type}-color-#{$key});
}

/// Get any - just - color value from $colors (or any) Sass map.
/// @param {string} $key - The key name of the color.
/// @param {string} $type - The type of the color group (base, dark, etc.).
/// @param {map} $map - The map to get the color from.
/// @return {color} - The color value.
@function color-value(
  $key,
  $type: 'base',
  $map: $colors
) {
  @if not map.has-key($map, $type, $key) {
    @error 'The #{$key} key name doesn\'t exist under #{$type} at the specified map (default: $colors).';
  }

  @if map.get($map, $type, $key) == null {
    @return null;
  }

  @return map.get($map, $type, $key);
}

/// Get a white or black contrast color for any color (on WCAG standards).
/// Thanks for David Halford for this function: https://codepen.io/davidhalford/pen/ALrbEP
/// @param {color} $color - The color to get the contrast color.
/// @return {color} - The contrast color.
@function color-contrast($color) {
  $color-brightness: math.round((color.channel($color, 'red', $space: rgb) * 299) + (color.channel($color, 'green', $space: rgb) * 587) + math.div(color.channel($color, 'blue', $space: rgb) * 114, 1000));
  $light-color: math.round((color.channel(hsl(0deg 0% 100%), 'red', $space: rgb) * 299) + (color.channel(hsl(0deg 0% 100%), 'green', $space: rgb) * 587) + math.div(color.channel(hsl(0deg 0% 100%), 'blue', $space: rgb) * 114, 1000));

  @if math.abs($color-brightness) < math.div($light-color, 2) {
    @return hsl(0 0% 100%);
  } @else {
    @return hsl(0 100% 0%);
  }
}
