import define_default, { extend } from "./define.js";
import { Color, Rgb, rgbConvert } from "./color.js";
import { degrees, radians } from "./math.js";
var K = 18, Xn = .96422, Yn = 1, Zn = .82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1;
function labConvert(e) {
	if (e instanceof Lab) return new Lab(e.l, e.a, e.b, e.opacity);
	if (e instanceof Hcl) return hcl2lab(e);
	e instanceof Rgb || (e = rgbConvert(e));
	var y = rgb2lrgb(e.r), b = rgb2lrgb(e.g), S = rgb2lrgb(e.b), C = xyz2lab((.2225045 * y + .7168786 * b + .0606169 * S) / Yn), w, T;
	return y === b && b === S ? w = T = C : (w = xyz2lab((.4360747 * y + .3850649 * b + .1430804 * S) / Xn), T = xyz2lab((.0139322 * y + .0971045 * b + .7141733 * S) / Zn)), new Lab(116 * C - 16, 500 * (w - C), 200 * (C - T), e.opacity);
}
function lab(e, y, b, x) {
	return arguments.length === 1 ? labConvert(e) : new Lab(e, y, b, x ?? 1);
}
function Lab(e, y, b, x) {
	this.l = +e, this.a = +y, this.b = +b, this.opacity = +x;
}
define_default(Lab, lab, extend(Color, {
	brighter(e) {
		return new Lab(this.l + K * (e ?? 1), this.a, this.b, this.opacity);
	},
	darker(e) {
		return new Lab(this.l - K * (e ?? 1), this.a, this.b, this.opacity);
	},
	rgb() {
		var e = (this.l + 16) / 116, y = isNaN(this.a) ? e : e + this.a / 500, b = isNaN(this.b) ? e : e - this.b / 200;
		return y = Xn * lab2xyz(y), e = Yn * lab2xyz(e), b = Zn * lab2xyz(b), new Rgb(lrgb2rgb(3.1338561 * y - 1.6168667 * e - .4906146 * b), lrgb2rgb(-.9787684 * y + 1.9161415 * e + .033454 * b), lrgb2rgb(.0719453 * y - .2289914 * e + 1.4052427 * b), this.opacity);
	}
}));
function xyz2lab(e) {
	return e > t3 ? e ** (1 / 3) : e / t2 + t0;
}
function lab2xyz(e) {
	return e > t1 ? e * e * e : t2 * (e - t0);
}
function lrgb2rgb(e) {
	return 255 * (e <= .0031308 ? 12.92 * e : 1.055 * e ** (1 / 2.4) - .055);
}
function rgb2lrgb(e) {
	return (e /= 255) <= .04045 ? e / 12.92 : ((e + .055) / 1.055) ** 2.4;
}
function hclConvert(e) {
	if (e instanceof Hcl) return new Hcl(e.h, e.c, e.l, e.opacity);
	if (e instanceof Lab || (e = labConvert(e)), e.a === 0 && e.b === 0) return new Hcl(NaN, 0 < e.l && e.l < 100 ? 0 : NaN, e.l, e.opacity);
	var y = Math.atan2(e.b, e.a) * degrees;
	return new Hcl(y < 0 ? y + 360 : y, Math.sqrt(e.a * e.a + e.b * e.b), e.l, e.opacity);
}
function hcl(e, y, b, x) {
	return arguments.length === 1 ? hclConvert(e) : new Hcl(e, y, b, x ?? 1);
}
function Hcl(e, y, b, x) {
	this.h = +e, this.c = +y, this.l = +b, this.opacity = +x;
}
function hcl2lab(e) {
	if (isNaN(e.h)) return new Lab(e.l, 0, 0, e.opacity);
	var y = e.h * radians;
	return new Lab(e.l, Math.cos(y) * e.c, Math.sin(y) * e.c, e.opacity);
}
define_default(Hcl, hcl, extend(Color, {
	brighter(e) {
		return new Hcl(this.h, this.c, this.l + K * (e ?? 1), this.opacity);
	},
	darker(e) {
		return new Hcl(this.h, this.c, this.l - K * (e ?? 1), this.opacity);
	},
	rgb() {
		return hcl2lab(this).rgb();
	}
}));
export { lab as default, hcl };
