import { Vector2 } from "three";

export default function getCenteroidPoint(points: Vector2[]): Vector2 | null {
    if (points.length < 3) return null;

    let minZ = points[0].y;
    let maxZ = points[0].y;
    for (let i = 1; i < points.length; i++) {
        minZ = Math.min(minZ, points[i].y);
        maxZ = Math.max(maxZ, points[i].y);
    }

    const scanZ = minZ + (maxZ - minZ) * 0.51;

    const intersections: number[] = [];

    for (let i = 0; i < points.length; i++) {
        const p1 = points[i];
        const p2 = points[(i + 1) % points.length];

        if (p1.y === p2.y) continue;

        const [top, bottom] = p1.y > p2.y ? [p1, p2] : [p2, p1];

        if (scanZ >= bottom.y && scanZ < top.y) {
            const t = (scanZ - bottom.y) / (top.y - bottom.y);
            const x = bottom.x + t * (top.x - bottom.x);
            intersections.push(x);
        }
    }

    intersections.sort((a, b) => a - b);

    if (intersections.length >= 2) {
        const x = (intersections[0] + intersections[1]) / 2;
        return new Vector2(x, scanZ);
    }

    let x = 0,
        z = 0;
    for (const p of points) {
        x += p.x;
        z += p.y;
    }
    x /= points.length;
    z /= points.length;
    return new Vector2(x, z);
}
