import { clamp01 } from "../../../math/clamp01.js";
import { v2_distance_sqr } from "../../vec2/v2_distance_sqr.js";

/**
 * Computes squared shortest distance between a line segment(defined by 2 points) and a point
 * @param {number} x0
 * @param {number} y0
 * @param {number} x1
 * @param {number} y1
 * @param {number} px
 * @param {number} py
 */
export function line2_distance_to_point_sqr(
    x0, y0,
    x1, y1,
    px, py
) {
    // get line delta
    const line_delta_x = x1 - x0;
    const line_delta_y = y1 - y0;

    // find closest point
    const sp0_x = px - x0;
    const sp0_y = py - y0;

    //
    const d2 = line_delta_x * line_delta_x + line_delta_y * line_delta_y;

    const d3 = line_delta_x * sp0_x + line_delta_y * sp0_y;

    const t = clamp01(d3 / d2);

    // compute point on the line
    const lp_x = line_delta_x * t + x0;
    const lp_y = line_delta_y * t + y0;

    // compute distance from the point in question to the point on the line
    return v2_distance_sqr(px, py, lp_x, lp_y);
}
