#version 440 core

layout (location = 0) out vec4 FragColor;
layout (location = 1) out vec4 BrightColor;

//const vec3 waterColour = vec3(0.604, 0.867, 0.851);
const vec3 lightDirection = normalize(vec3(0.5, 0.5, 1.0)); // Direction of the light source


in vec3 vs_position;
in vec3 vs_color;
in vec2 vs_texcoord;
in vec3 vs_normal;
in vec3 world_position;


uniform vec3 camera_position;
uniform samplerCube skybox; // Skybox cubemap
uniform sampler2D waterTexture; // Water texture

//reflection was done by the tutorial https://learnopengl.com/Advanced-OpenGL/Cubemaps

void main()
{
    
    // Sample the water texture color
    vec3 waterColour = texture(waterTexture, vs_texcoord).rgb;

    // Calculate the intensity of the light based on the dot product between the normal and light direction
    float intensity = max(dot(normalize(vs_normal), lightDirection), 0.0);
    
    // Apply the lighting to the water color
    vec3 illuminatedColor = waterColour * intensity;

    // Calculate the view direction
    vec3 viewDir = normalize(world_position - camera_position);

    // Calculate the reflection direction
    vec3 reflectionDir = reflect(viewDir, normalize(vs_normal));

    // Sample the reflection texture
    vec4 reflectionColor = texture(skybox, reflectionDir);

    // Mix the water color and reflection based on the Fresnel effect
    float fresnel = pow(1.0 - max(dot(viewDir, normalize(vs_normal)), 0.0), 2.0);
    vec3 finalColor = mix(illuminatedColor, reflectionColor.rgb, fresnel * 0.5);

    // fog parameters
    vec3 fogColor = vec3(0.f, 0.f, 0.f);
    float fogStart = 10.0f;
    float fogEnd = 30.0f;
    // Fog calculation
    float distance = length(camera_position - vs_position);
    float fogFactor = clamp((fogEnd - distance) / (fogEnd - fogStart), 0.0, 1.0);
    finalColor = mix(fogColor, finalColor, fogFactor);

    //vec4 reflectionColor = texture(reflectionTexture, TexCoord);
    FragColor = vec4(finalColor, 1.0);
    float brightness = dot(FragColor.rgb, vec3(0.2126, 0.7152, 0.0722));
    if(brightness > 0.5)
        BrightColor = vec4(FragColor.rgb, 1.0);
    else
        BrightColor = vec4(0.0, 0.0, 0.0, 1.0);
}