// Define the RGB color type
type RGBColor = [number, number, number];

// Helper function to convert an sRGB component to linear RGB
function sRGBtoLinear(component: number): number {
	const _component = component / 255;
	if (_component <= 0.04045) {
		return _component / 12.92;
	}
	return ((_component + 0.055) / 1.055) ** 2.4;
}

// Helper function to calculate relative luminance
function getRelativeLuminance(r: number, g: number, b: number): number {
	const linearR = sRGBtoLinear(r);
	const linearG = sRGBtoLinear(g);
	const linearB = sRGBtoLinear(b);

	return 0.2126 * linearR + 0.7152 * linearG + 0.0722 * linearB;
}

// Helper function to calculate contrast ratio
function getContrastRatio(color1: RGBColor, color2: RGBColor): number {
	const luminance1 = getRelativeLuminance(color1[0], color1[1], color1[2]);
	const luminance2 = getRelativeLuminance(color2[0], color2[1], color2[2]);

	// Calculate contrast ratio by ensuring the lighter color is in the numerator
	return (
		(Math.max(luminance1, luminance2) + 0.05) /
		(Math.min(luminance1, luminance2) + 0.05)
	);
}

// Main function to check contrast between two colors
export function hasEnoughContrast(
	color1: RGBColor,
	color2: RGBColor,
	minContrastRatio = 3,
): boolean {
	const contrastRatio = getContrastRatio(color1, color2);
	return contrastRatio >= minContrastRatio;
}
