import { max3 } from "../../math/max3.js";
import { compute_max_saturation } from "./compute_max_saturation.js";
import { oklab_to_linear_srgb } from "./oklab_to_linear_srgb.js";

const rgb_at_max = [0, 0, 0];


/**
 * finds L_cusp and C_cusp for a given hue
 * a and b must be normalized so a^2 + b^2 == 1
 * @param {number[]} output [L, C]
 * @param {number} a
 * @param {number} b
 *
 * @author Alex Goldring
 * @copyright Company Named Limited (c) 2026
 */
export function find_cusp(output, a, b) {
    // First, find the maximum saturation (saturation S = C/L)
    const S_cusp = compute_max_saturation(a, b);

    // Convert to linear sRGB to find the first point where at least one of r,g or b >= 1:
    oklab_to_linear_srgb(rgb_at_max, 1, S_cusp * a, S_cusp * b);

    const max_component = max3(rgb_at_max[0], rgb_at_max[1], rgb_at_max[2]);

    const L_cusp = Math.cbrt(1. / max_component);
    const C_cusp = L_cusp * S_cusp;

    output[0] = L_cusp;
    output[1] = C_cusp;
}