/* stylelint-disable number-max-precision */

////
/// @author Giana Blantin
////

/// Tries to fix contrast of both colors by weighted balance (0–100).
/// 0 = don't change first color, change second color;
/// 100 = change first color, don't change second color
/// @link https://www.w3.org/TR/2016/NOTE-WCAG20-TECHS-20161007/G18#G18-procedure
/// @since 1.12.0 - The Sith
/// @param {Color} $color1 - 1st color to test the contrast against
/// @param {Color} $color2 - 2nd color to test the contrast against
/// @param {String | Number} $min-ratio ["AA"] - minimum ratio to test against. Accepted values for this ratio argument are AA and AAALG (4.5:1), AALG (3:1) and AAA (7:1) or a number between 1 and 21.
/// @param {Number} $balance ["50"] - a number that lets you control how the colors are scaled to satisfy the contrast requirements
/// @return {List} - a list with both colors, use nth($result, 1) and nth($result, 2) to get colors
/// @throw Warning Your settings didn't work. Modifying first color or second color in an attempt to fix.
/// @example scss
///   // favoring $color1 change over $color2
///   fix-contrast(#aaf901, #bbffc8, 6, 70%)
///   // #460, #cfffd9
///
///   // splitting the difference between both colors equally
///   fix-contrast(#e5eae1, #9dffff, 3)
///   // #8b9089, #ceffff
///
///   // usage
///   .image-caption {
///      $colors: fix-contrast(gray, blue, 5, 60%);
///      background: nth($colors, 2);
///      color: nth($colors, 1);
///   }
@function fix-contrast($color1, $color2, $min-ratio: "AA", $balance: 50, $test: false) {
	@if (not check-contrast($color1, $color2, $min-ratio)) {
		// Fix colors
		$color-fixed-1: fix-color($color1, $color2, $min-ratio);
		$color-fixed-2: fix-color($color2, $color1, $min-ratio);

		// We're fixing both colors, then mixing back the original color using the native Sass function. Easy-peasy
		$color1: mix($color-fixed-1, $color1, $balance);
		$color2: mix($color2, $color-fixed-2, $balance);

		// If the current configuration doesn't work, try to fix it
		@if (not check-contrast($color1, $color2, $min-ratio)) {
			// This happens if, again, we reach #fff or #000 before we want to
			@if (not in-bounds(luminance($color-fixed-2), .00002, .99936)) {
				// So we scale the opposite color to compensate
				$color1: fix-color($color1, $color2, $min-ratio);

				@if not $test {
					@warn "Your settings didn't work. Modifying first color in an attempt to fix.";
				}
			}
			@if (not in-bounds(luminance($color-fixed-1), .00002, .99936)) {
				$color2: fix-color($color2, $color1, $min-ratio);

				@if not $test {
					@warn "Your settings didn't work. Modifying second color in an attempt to fix.";
				}
			}
		}
	}

	@return $color1, $color2;
}
