function distancePointToSegment(p, seg) {
const [px, py] = p;
const [[ax, ay], [bx, by]] = seg;
const dx = bx - ax;
const dy = by - ay;
const segmentLengthSquared = dx * dx + dy * dy;
let t = ((px - ax) * dx + (py - ay) * dy) / segmentLengthSquared;
t = Math.max(0, Math.min(1, t));
const closestX = ax + t * dx;
const closestY = ay + t * dy;
const distanceX = px - closestX;
const distanceY = py - closestY;
return Math.sqrt(distanceX * distanceX + distanceY * distanceY);
}