import { max2 } from "../../../math/max2.js";

/**
 * Compute squared distance to point, value is negative if the point is inside the box
 * @param {number} x0
 * @param {number} y0
 * @param {number} x1
 * @param {number} y1
 * @param {number} point_x
 * @param {number} point_y
 * @returns {number}
 */
export function aabb2_signed_distance_sqr_to_point(
    x0, y0,
    x1, y1,
    point_x, point_y
) {
    //do projection
    const xp0 = x0 - point_x;
    const xp1 = point_x - x1;
    const yp0 = y0 - point_y;
    const yp1 = point_y - y1;

    //calculate separation in each axis
    let dx = max2(xp0, xp1);
    let dy = max2(yp0, yp1);

    if (dx >= 0 || dy >= 0) {
        // non-penetrating, clamp axis
        dx = max2(dx, 0);
        dy = max2(dy, 0);

        //straight-line distance
        return (dx * dx + dy * dy);
    } else {

        //penetration, negative distance, pick nearest axis
        if (Math.abs(dx) > Math.abs(dy)) {
            return -(dy * dy)
        } else {
            return -dx * dx;
        }

    }
}
