import type { Color } from '../types/color';

/**
 * Convert an array of of sRGB values where in-gamut values are in the range
 * [0 - 1] to linear light (un-companded) form.
 * Extended transfer function:
 *  For negative values, linear portion is extended on reflection of axis,
 *  then reflected power function is used.
 *
 * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document
 * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang).
 * @see https://en.wikipedia.org/wiki/SRGB
 */
export function lin_sRGB(RGB: Color): Color {
	return [
		lin_sRGB_channel(RGB[0]),
		lin_sRGB_channel(RGB[1]),
		lin_sRGB_channel(RGB[2]),
	];
}

function lin_sRGB_channel(val: number): number {
	const sign = val < 0 ? -1 : 1;
	const abs = Math.abs(val);

	if (abs <= 0.04045) {
		return val / 12.92;
	}

	return sign * (Math.pow((abs + 0.055) / 1.055, 2.4));
}
