precision highp float;

varying vec3 vWorldPosition;

uniform vec3 uColor;
uniform float uFadeDistance; // max distance inward from edge
uniform vec2 uEdges[64];     // polygon edges packed as pairs (start, end)
uniform int uEdgeCount;

float pointToSegmentDist(vec2 p, vec2 a, vec2 b) {
    vec2 pa = p - a;
    vec2 ba = b - a;
    float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
    return length(pa - ba * h);
}

void main() {
    vec2 fragXZ = vWorldPosition.xz;

    float minDist = 1e6;
    for (int i = 0; i < 64; i++) {
        if (i >= uEdgeCount) break;
        vec2 a = uEdges[i*2 + 0];
        vec2 b = uEdges[i*2 + 1];
        float d = pointToSegmentDist(fragXZ, a, b);
        minDist = min(minDist, d);
    }

    float alpha = smoothstep(uFadeDistance, 0.0, minDist);

    gl_FragColor = vec4(uColor, alpha);
}
