import { max2 } from "../../../core/math/max2.js";
import { min2 } from "../../../core/math/min2.js";
import { spline3_hermite_bounds } from "../../../core/math/spline/spline3_hermite_bounds.js";

const temp_bounds = new Float32Array(2);

/**
 * Compute a bounding box for a given curve.
 * X-axis is time, Y-axis is value.
 * @param {AABB2} out
 * @param {AnimationCurve} curve
 *
 * @author Alex Goldring
 * @copyright Company Named Limited (c) 2026
 */
export function animation_curve_compute_aabb(out, curve) {
    let x0 = Number.POSITIVE_INFINITY;
    let x1 = Number.NEGATIVE_INFINITY;
    let y0 = Number.POSITIVE_INFINITY;
    let y1 = Number.NEGATIVE_INFINITY;

    const keys = curve.keys;
    const key_count = keys.length;

    if (key_count > 0) {

        let previous = keys[0];
        x0 = x1 = previous.time;
        y0 = y1 = previous.value;

        for (let i = 1; i < key_count; i++) {
            const keyframe = keys[i];

            const time_delta = keyframe.time - previous.time;

            spline3_hermite_bounds(temp_bounds, 0, 1,
                previous.value, keyframe.value,
                previous.outTangent * time_delta,
                keyframe.inTangent * time_delta
            );

            x0 = min2(x0, keyframe.time)
            x1 = max2(x1, keyframe.time)

            y0 = min2(y0, temp_bounds[0]);
            y1 = max2(y1, temp_bounds[1]);

            previous = keyframe;
        }

    }

    out.set(x0, y0, x1, y1);
}