@use 'sass:math';
@use 'sass:meta';
@use 'sass:color';
@use '../utils/math' as *;

////
/// WCAG relative luminance and contrast ratio.
/// Extracted from `functions` so the shade generators can use them without a cycle;
/// both are still exported from the `color` module exactly as before.
/// @package theming
////

/// Calculates the linear channel value for a given sRGB color.
/// @access private
/// @group Color
/// @param {Number} $value - The sRGB color
/// @returns {Number} The calculated linear channel value
@function _lcv($value) {
    // stylelint-disable number-max-precision
    @return if($value < 0.03928, math.div($value, 12.92), math.pow(math.div($value + 0.055, 1.055), 2.4));
}

/// Calculates the luminance for a given color.
/// @access public
/// @group Color
/// @param {Color} $color - The color to calculate luminance for.
///
/// @example scss
///   $white: luminance(#fff); // 1
///   $blue: luminance(#09f); // 0.3
///   $black: luminance(#000); // 0
///
/// @returns {Number | String} The calculated luminance of a given color
/// @link https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests. WCAG 2.0 Contrast Ratio
@function luminance($color) {
    @if meta.type-of($color) == 'color' {
        $r: math.div(color.channel($color, 'red', $space: rgb), 255);
        $g: math.div(color.channel($color, 'green', $space: rgb), 255);
        $b: math.div(color.channel($color, 'blue', $space: rgb), 255);

        @return 0.2126 * _lcv($r) + 0.7152 * _lcv($g) + 0.0722 * _lcv($b);
    }

    @return $color;
}

/// Calculates the contrast ratio between two colors.
/// @access public
/// @group Color
/// @param {Color} $background - The background color.
/// @param {Color} $foreground - The foreground color.
///
/// @example scss
///   $conrast: contrast(#09f, #000); // 7
///
/// @returns {Number} The contrast ratio between the background and foreground colors.
/// @require {function} luminance
/// @require {function} to-fixed
/// @link https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests WCAG 2.0 Contrast Ratio
@function contrast($background, $foreground) {
    $backLum: luminance($background) + 0.05;
    $foreLum: luminance($foreground) + 0.05;

    @return to-fixed(math.div(math.max($backLum, $foreLum), math.min($backLum, $foreLum)));
}
