#version 330 core

out vec4 FragColor;
in vec3 worldPos;

uniform vec3 sunDirection;
uniform float sunHeight;
uniform float time;

void main()
{
    vec3 viewDir = normalize(worldPos);
    
    // Base sky colors
    vec3 daySkyTop = vec3(0.2, 0.5, 0.9);        // Deep blue at top
    vec3 daySkyHorizon = vec3(0.5, 0.7, 1.0);    // Lighter blue at horizon
    vec3 nightSkyTop = vec3(0.01, 0.02, 0.05);   // Very dark blue/black
    vec3 nightSkyBottom = vec3(0.05, 0.08, 0.15); // Slightly lighter at horizon
    
    // Sunset/sunrise colors
    vec3 sunsetOrange = vec3(1.0, 0.5, 0.2);
    vec3 sunsetPink = vec3(1.0, 0.3, 0.5);
    vec3 sunsetPurple = vec3(0.6, 0.2, 0.6);
    
    // Calculate gradient from top to horizon based on view direction
    float viewHeight = viewDir.y;
    float horizonBlend = smoothstep(-0.1, 0.3, viewHeight);
    
    // Day/night transition based on sun height
    float dayNightBlend = smoothstep(-0.3, 0.3, sunHeight);
    
    // Base sky color (blue during day, dark at night)
    vec3 baseSkyTop = mix(nightSkyTop, daySkyTop, dayNightBlend);
    vec3 baseSkyHorizon = mix(nightSkyBottom, daySkyHorizon, dayNightBlend);
    vec3 baseSky = mix(baseSkyHorizon, baseSkyTop, horizonBlend);
    
    // Calculate angle to sun position
    float angleToSun = dot(viewDir, normalize(sunDirection));
    float distanceToSun = acos(max(-1.0, min(1.0, angleToSun)));
    
    // Only apply sunset colors when sun is near horizon
    float horizonFactor = 1.0 - abs(sunHeight);
    horizonFactor = pow(horizonFactor, 0.8);
    
    // Sunset/sunrise gradient (only near sun and when sun is at horizon)
    float sunGlow = exp(-distanceToSun * 1.5);
    float sunGlowWide = exp(-distanceToSun * 0.8);
    
    // Twilight effect - glow remains even when sun is slightly below horizon
    float twilightFactor = smoothstep(-0.4, 0.1, sunHeight);
    
    // Blend sunset colors only near the sun
    vec3 sunsetColor = mix(sunsetPurple, sunsetOrange, sunGlow);
    sunsetColor = mix(sunsetColor, sunsetPink, 0.3);
    
    // Apply sunset glow only when sun is at/near horizon
    vec3 finalSky = mix(baseSky, sunsetColor, sunGlowWide * horizonFactor * twilightFactor * 0.8);
    
    // Add extra glow right at sun position
    finalSky = mix(finalSky, sunsetOrange * 1.2, sunGlow * horizonFactor * twilightFactor * 0.5);
    
    FragColor = vec4(finalSky, 1.0);
}
