struct VertexInput {
    @location(0) position: vec3<f32>,
    @location(1) tex_coords: vec2<f32>,
};

struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) tex_coords: vec2<f32>,
    @location(1) world_pos: vec3<f32>,
};

struct Uniforms {
    view: mat4x4<f32>,
    projection: mat4x4<f32>,
    camera_position: vec4<f32>,
};

struct TextUniforms {
    model: mat4x4<f32>,
    color: vec4<f32>,
    outline_color: vec4<f32>,
    outline_width: f32,
    smoothing: f32,
    _padding: vec2<f32>,
};

@group(0) @binding(0)
var<uniform> uniforms: Uniforms;

@group(1) @binding(0)
var<uniform> text_uniforms: TextUniforms;

@group(2) @binding(0)
var font_texture: texture_2d<f32>;

@group(2) @binding(1)
var font_sampler: sampler;

@vertex
fn vs_main(in: VertexInput) -> VertexOutput {
    var out: VertexOutput;

    let world_position = text_uniforms.model * vec4<f32>(in.position, 1.0);
    out.world_pos = world_position.xyz;
    out.position = uniforms.projection * uniforms.view * world_position;
    out.tex_coords = in.tex_coords;

    return out;
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let sdf_value = textureSample(font_texture, font_sampler, in.tex_coords).r;

    let distance = sdf_value - 0.5;

    let smoothing = text_uniforms.smoothing;
    let alpha = smoothstep(-smoothing, smoothing, distance);

    var final_color = text_uniforms.color;

    if (text_uniforms.outline_width > 0.0) {
        let outline_distance = distance + text_uniforms.outline_width;
        let outline_alpha = smoothstep(-smoothing, smoothing, outline_distance);

        let outline_factor = smoothstep(
            -text_uniforms.outline_width - smoothing,
            -text_uniforms.outline_width + smoothing,
            distance
        );

        final_color = mix(text_uniforms.outline_color, text_uniforms.color, outline_factor);

        let final_alpha = max(alpha, outline_alpha * text_uniforms.outline_color.a);
        final_color.a *= final_alpha;
    } else {
        final_color.a *= alpha;
    }

    if (final_color.a < 0.01) {
        discard;
    }

    return final_color;
}
