@use 'sass:list';
@use '../contrast-ratio/contrast-ratio' as cr;
@use '../../../core/error/error-to-string';

/// Returns the color from a list of colors that has the highest contrast ratio with a reference color.
/// If the list is empty, an error is thrown. If the list has one color, that color is returned.
///
/// @group Theming
///
/// @param {Color} $reference-color
/// @param {List} $colors — A list of colors to compare against the reference color
/// @return {Color} The color with the highest contrast ratio between the reference color and the color list
///
/// @example scss
/// 	.card {
/// 		background: daff-color($primary, 30);
/// 		border-color: daff-max-contrast(daff-color($primary, 30), (daff-color($secondary, 70), daff-color($accent, 50)));
/// 	}
///
@function daff-max-contrast(
	$reference-color,
	$colors: ()
) {
	@if(list.length($colors) == 0) {
		@return error-to-string.error-to-string(
			'Cannot calculate max contrast for `' + $reference-color + '`Provide at least one color to compare against.'
		);
	}
	@else if(list.length($colors) == 1) {
		@return list.nth($colors, 1);
	}
	@else {
		$max-contrast: -1;
		$max-contrast-color: null;

		@each $color in $colors {
			$current-contrast: cr.daff-contrast-ratio($reference-color, $color);

			@if($current-contrast > $max-contrast) {
				$max-contrast: $current-contrast;
				$max-contrast-color: $color;
			}
		}

		@return $max-contrast-color;
	}
}
