#ifndef AMBIENT_LIGHT_GLSL_
#define AMBIENT_LIGHT_GLSL_

#include "worldFrameData.glsl"

float computeDirectional(vec3 pos, vec3 normal, vec3 lightDir, float specular)
{
    vec3 viewDir = normalize(-pos);
    vec3 reflectDir = reflect(-normalize(lightDir), normal);

    return max(0.0, dot(normal, normalize(lightDir)))
        + specular * pow(max(dot(viewDir, reflectDir), 0.0), LIGHT_SHININESS);
}

float computeAmbientFactor(vec3 pos, float ambientLightLevel)
{
    float realPosZ = pos.z + uFrameData.playerZ;
    float distFromSunlight = max(0.0, -realPosZ);
    float ambientFactor = 1.0 - (distFromSunlight / GLSL_SUNLIGHT_MAX_DEPTH);
    ambientFactor = clamp(ambientFactor, 0.0, 1.0);
    ambientFactor *= ambientLightLevel;

    return ambientFactor;
}

vec3 computeAmbientLight(vec3 pos, vec3 normal, float specular, float ambientLightLevel, vec3 sunIntensity)
{
    float ambientFactor = computeAmbientFactor(pos, ambientLightLevel);

    vec3 lightDir = (uFrameData.skybox * vec4(0.0, 1.0, 0.0, 0.0)).xyz;

    vec3 ambientLight = uFrameData.ambientColor * (
        vec3(max(0.0, computeDirectional(
            pos,
            normal,
            lightDir,
            specular
        ))) * sunIntensity * ambientFactor + vec3(GLSL_AMBIENT_FACTOR * ambientFactor)
    );

    ambientLight = max(ambientLight, vec3(0.002, 0.002, 0.01));

    return ambientLight;
}

#endif