import { assert } from "../../assert.js";
import { clamp01 } from "../../math/clamp01.js";
import { lerp } from "../../math/lerp.js";
import { Color } from "../Color.js";
import { linear_srgb_to_okhsv } from "../oklab/linear_srgb_to_okhsv.js";
import { okhsv_to_linear_srgb } from "../oklab/okhsv_to_linear_srgb.js";

const hsv_0 = [0, 0, 0];
const hsv_1 = [0, 0, 0];
const hsv_2 = [0, 0, 0];

/**
 * Performs linear interpolation of two colors in perceptual color space,
 * Useful for palette generation and other use cases where perceptual likeness is important
 * @param {Color} color_0
 * @param {Color} color_1
 * @param {number} t
 * @returns {Color}
 */
export function color_lerp(color_0, color_1, t) {
    assert.defined(color_0, 'color_0');
    assert.defined(color_1, 'color_1');
    assert.isNumber(t, 't');

    const r = new Color();

    linear_srgb_to_okhsv(hsv_0, color_0.r, color_0.g, color_0.b);
    linear_srgb_to_okhsv(hsv_1, color_1.r, color_1.g, color_1.b);

    const _t = clamp01(t);

    for (let i = 0; i < 3; i++) {
        hsv_2[i] = lerp(hsv_0[i], hsv_1[i], _t);
    }

    okhsv_to_linear_srgb(r, ...hsv_2);
    r.a = lerp(color_0.a, color_1.a, _t);

    return r;
}