#version 300 es
precision highp float;
precision highp int;

uniform vec2 uResolution;
uniform float uTime;
uniform float uOpen;
uniform int uLightMode;
uniform int uCamMode;

out vec4 fragColor;

const float PI  = 3.14159265359;
const float TAU = 6.28318530718;

// ---------------------------------------------------------------------------
// Math, Hashes & Ultra-Crisp Multi-Octave Gyroid FBM
// ---------------------------------------------------------------------------
mat2 rot2(float a) {
    float c = cos(a), s = sin(a);
    return mat2(c, -s, s, c);
}

float sq(float x) { return x * x; }

float hash11(float p) {
    p = fract(p * 0.1031);
    p *= p + 33.33;
    p *= p + p;
    return fract(p);
}

float hash21(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * 0.1031);
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.x + p3.y) * p3.z);
}

float hash31(vec3 p) {
    p = fract(p * 0.1031);
    p += dot(p, p.zyx + 31.32);
    return fract((p.x + p.y) * p.z);
}

vec3 hash33(vec3 p) {
    p = fract(p * vec3(0.1031, 0.1030, 0.0973));
    p += dot(p, p.yxz + 33.33);
    return fract((p.xxy + p.yxx) * p.zyx);
}

float vnoise3(vec3 p) {
    vec3 i = floor(p);
    vec3 f = fract(p);
    f = f * f * (3.0 - 2.0 * f);

    float n000 = hash31(i + vec3(0.0, 0.0, 0.0));
    float n100 = hash31(i + vec3(1.0, 0.0, 0.0));
    float n010 = hash31(i + vec3(0.0, 1.0, 0.0));
    float n110 = hash31(i + vec3(1.0, 1.0, 0.0));
    float n001 = hash31(i + vec3(0.0, 0.0, 1.0));
    float n101 = hash31(i + vec3(1.0, 0.0, 1.0));
    float n011 = hash31(i + vec3(0.0, 1.0, 1.0));
    float n111 = hash31(i + vec3(1.0, 1.0, 1.0));

    float nx00 = mix(n000, n100, f.x);
    float nx10 = mix(n010, n110, f.x);
    float nx01 = mix(n001, n101, f.x);
    float nx11 = mix(n011, n111, f.x);
    float nxy0 = mix(nx00, nx10, f.y);
    float nxy1 = mix(nx01, nx11, f.y);
    return mix(nxy0, nxy1, f.z);
}

float fbmStone(vec3 p) {
    float v = 0.0;
    float a = 0.52;
    const mat3 m = mat3(
         0.80,  0.60,  0.00,
        -0.60,  0.80,  0.00,
         0.00,  0.00,  1.00
    );
    for (int i = 0; i < 3; i++) {
        v += a * vnoise3(p);
        p = m * p * 2.06 + vec3(17.1, 31.7, 11.3);
        a *= 0.5;
    }
    return v;
}

// Fast, razor-sharp 5-octave 3D Gyroid FBM for billowing cosmic nebula wisps
float gyroid(vec3 p) {
    return dot(sin(p), cos(p.yzx));
}

float nebulaFbm(vec3 p) {
    float v = 0.0;
    float a = 0.50;
    float norm = 0.0;
    const mat3 m = mat3(
         0.00,  0.80,  0.60,
        -0.80,  0.36, -0.48,
        -0.60, -0.48,  0.64
    );
    for (int i = 0; i < 5; i++) {
        float g = gyroid(p);
        // Blend smooth + subtle billow ridge for Hubble-like cosmic dust filaments
        v += a * (0.5 + 0.35 * g + 0.15 * (1.0 - abs(g)));
        norm += a;
        p = m * p * 2.08 + vec3(1.7, -2.3, 1.1) + g * 0.28;
        a *= 0.52;
    }
    return v / norm;
}

// High-frequency filamentary curl-wisps (3 fast gyroid octaves)
float nebulaWisps(vec3 p) {
    float v = 0.0;
    float a = 0.55;
    const mat3 m = mat3(
         0.80,  0.60,  0.00,
        -0.48,  0.64,  0.60,
         0.36, -0.48,  0.80
    );
    for (int i = 0; i < 3; i++) {
        float g = gyroid(p);
        v += a * (1.0 - abs(g) * 0.65);
        p = m * p * 2.18 + vec3(-1.4, 2.1, -0.9) + g * 0.42;
        a *= 0.50;
    }
    return clamp(v * 0.72, 0.0, 1.0);
}

float smin(float a, float b, float k) {
    float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);
    return mix(b, a, h) - k * h * (1.0 - h);
}

// ---------------------------------------------------------------------------
// Scene SDF: Carved Dark Stone Pedestal & Temple Chamber
// Material IDs: 1.0 = Pedestal stone, 2.0 = Temple floor, 3.0 = Temple walls/stairs
// ---------------------------------------------------------------------------
float sdCappedCylinder(vec3 p, float h, float r) {
    vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(r, h);
    return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));
}

float sdPedestal(vec3 p) {
    float r = length(p.xz);
    if (r > 1.85 || p.y > -0.45) {
        return max(r - 1.40, p.y + 0.65);
    }

    float ang = atan(p.z, p.x);

    // Chipped octagonal weathered stone rim
    float octFacet = 0.028 * cos(8.0 * ang + 0.39);
    float chip = (vnoise3(p * 4.2) - 0.5) * 0.045 + (vnoise3(p * 11.0) - 0.5) * 0.016;

    // 1. Wide beveled altar top slab (y from -0.90 to -0.68)
    float yTop = p.y - (-0.79);
    float topBevel = smoothstep(-0.11, 0.09, yTop) * 0.07;
    float rTop = 1.24 + octFacet + topBevel + chip * 1.25;
    float basin = smoothstep(0.72, 0.12, r) * 0.025 * smoothstep(-0.74, -0.67, p.y);
    float dTop = sdCappedCylinder(vec3(p.x, yTop + basin, p.z), 0.105, rTop) - 0.018;

    // 2. Ornate concave waist / frieze with deep carved scrollwork (y from -1.30 to -0.88)
    float yWaist = p.y - (-1.09);
    float waistProfile = 0.92 + 0.16 * pow(max(abs(yWaist) / 0.21, 1e-4), 1.5);
    float scrollA = sin(10.0 * ang + sin(14.0 * yWaist) * 1.5);
    float scrollB = cos(20.0 * ang) * sin(22.0 * yWaist);
    float friezeBand = smoothstep(0.21, 0.13, abs(yWaist));
    float reliefWaist = (0.036 * scrollA + 0.018 * scrollB) * friezeBand;
    float dWaist = sdCappedCylinder(vec3(p.x, yWaist, p.z), 0.22, waistProfile + octFacet * 0.6 + reliefWaist + chip * 0.5);

    // 3. Flared lower plinth with gothic pointed-arch relief (y from -1.86 to -1.26)
    float yBase = p.y - (-1.56);
    float baseFlare = 0.96 + 0.28 * smoothstep(0.28, -0.30, yBase);
    float archSector = abs(fract(ang * 6.0 / TAU + 0.5) - 0.5) * 2.0;
    float archCurve = smoothstep(0.065, 0.0, abs(yBase + 0.04 - (0.22 - 0.38 * sq(archSector))));
    float archInner = smoothstep(0.045, 0.0, abs(yBase + 0.13 - (0.15 - 0.30 * sq(archSector))));
    float reliefBase = (archCurve * 0.042 + archInner * 0.028) * smoothstep(0.29, 0.18, abs(yBase));
    float dBase = sdCappedCylinder(vec3(p.x, yBase, p.z), 0.30, baseFlare + octFacet * 0.8 + reliefBase + chip * 0.6);

    // Moulding collars
    float dRing1 = sdCappedCylinder(vec3(p.x, p.y + 0.91, p.z), 0.024, 1.12 + octFacet * 0.7 + chip * 0.4) - 0.012;
    float dRing2 = sdCappedCylinder(vec3(p.x, p.y + 1.28, p.z), 0.030, 1.00 + octFacet * 0.7 + chip * 0.4) - 0.014;

    float d = smin(dTop, dWaist, 0.04);
    d = smin(d, dBase, 0.05);
    d = smin(d, dRing1, 0.02);
    d = smin(d, dRing2, 0.02);
    return d * 0.80;
}

vec2 mapScene(vec3 p) {
    float dPed = sdPedestal(p);
    vec2 res = vec2(dPed, 1.0);

    float dFloor = p.y + 1.86;
    if (dFloor < res.x) {
        res = vec2(dFloor, 2.0);
    }

    float r = length(p.xz);
    if (r > 3.6) {
        float stairIdx = clamp(floor((r - 4.1) / 0.50), 0.0, 5.0);
        float stairH = -1.86 + stairIdx * 0.18;
        float dStair = max(p.y - stairH, 4.1 - r);
        float dWall = 8.0 - r;
        float ang = atan(p.z, p.x);
        float pAng = (floor(ang * 12.0 / TAU + 0.5)) * TAU / 12.0;
        vec2 pPos = vec2(cos(pAng), sin(pAng)) * 7.0;
        float dPillar = length(p.xz - pPos) - 0.38;
        float dTemple = min(min(dStair, dWall), dPillar);
        if (dTemple < res.x) {
            res = vec2(dTemple, 3.0);
        }
    }

    return res;
}

// Unit-sign tetrahedral normal
vec3 calcNormal(vec3 p) {
    const float e = 0.0028;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * mapScene(p + k.xyy * e).x +
        k.yyx * mapScene(p + k.yyx * e).x +
        k.yxy * mapScene(p + k.yxy * e).x +
        k.xxx * mapScene(p + k.xxx * e).x
    );
}

float calcSoftShadow(vec3 ro, vec3 rd, float tMin, float tMax) {
    float res = 1.0;
    float t = tMin;
    for (int i = 0; i < 16; i++) {
        float h = mapScene(ro + rd * t).x;
        res = min(res, 6.0 * h / t);
        t += clamp(h, 0.06, 0.45);
        if (res < 0.02 || t > tMax) break;
    }
    return clamp(res, 0.0, 1.0);
}

float calcAO(vec3 p, vec3 n) {
    float occ = 0.0;
    float sca = 1.0;
    for (int i = 0; i < 4; i++) {
        float h = 0.04 + 0.14 * float(i);
        float d = mapScene(p + h * n).x;
        occ += (h - d) * sca;
        sca *= 0.65;
    }
    return clamp(1.0 - 2.2 * occ, 0.08, 1.0);
}

vec2 iSphere(vec3 ro, vec3 rd, float rad) {
    float b = dot(ro, rd);
    float c = dot(ro, ro) - rad * rad;
    float h = b * b - c;
    if (h < 0.0) return vec2(-1.0);
    h = sqrt(h);
    return vec2(-b - h, -b + h);
}

// ---------------------------------------------------------------------------
// Crisp Multi-Octave Volumetric Cosmic Spiral Nebula (Hubble / 04.png look)
// ---------------------------------------------------------------------------
vec4 sampleNebula(vec3 pLocal, float phase, float breath, float sphereR) {
    float bScale = 1.0 + 0.13 * breath;
    vec3 q = pLocal / (sphereR * bScale);

    // Tilt galaxy slightly toward viewer so spiral structure & 3D depth pop
    q.yz = rot2(0.26) * q.yz;
    q.xz = rot2(-0.15) * q.xz;

    float r3 = length(q);
    if (r3 > 0.96) return vec4(0.0);

    // Seamless 3.0s galaxy rotation (inner swirls slightly faster via integer harmonic)
    float spin = TAU * phase;
    vec3 qRot = q;
    qRot.xy = rot2(-spin) * qRot.xy;

    float r2 = length(qRot.xy);
    float ang = atan(qRot.y, qRot.x);

    // Logarithmic spiral warp applied directly to 3D noise coordinates for true swirling clouds!
    float spiralTwist = 2.85 * log(r2 + 0.14);
    vec3 qSwirl = qRot;
    qSwirl.xy = rot2(spiralTwist) * qSwirl.xy;

    // 5-octave billowing gyroid nebula + 3-octave fine curly wisps
    float nBase = nebulaFbm(qSwirl * 3.8 + vec3(0.0, 0.0, 1.3));
    float nWisp = nebulaWisps(qSwirl * 7.8 + vec3(nBase * 2.2, -nBase * 1.8, 0.7));

    // Organic domain-warped 2-arm + 3-arm spiral galaxy envelope
    float swirlAng = ang - 3.7 * log(r2 + 0.11) + (nBase - 0.5) * 3.1 + (nWisp - 0.5) * 1.1;
    float arm2 = pow(max(0.5 + 0.5 * cos(2.0 * swirlAng), 0.0), 2.1);
    float arm3 = pow(max(0.5 + 0.5 * cos(3.0 * swirlAng + 1.4), 0.0), 2.6);
    float spiralMask = arm2 * 0.82 + arm3 * 0.48;

    // 3D volumetric cloud thickness (tighter near core, fuller billowing outer nebula clouds)
    float diskEnv = exp(-abs(q.z) * (2.6 + 2.2 * r2));
    float sphereEnv = smoothstep(0.95, 0.34, r3);

    // Crisp cloud-edge shaping: deep dark cosmic rifts right beside luminous billowing nebula banks!
    float cloudShape = smoothstep(0.36, 0.76, nBase * 0.62 + nWisp * 0.48);
    float fineFilaments = smoothstep(0.48, 0.86, nWisp) * smoothstep(0.32, 0.72, nBase);

    float mainCloud = spiralMask * diskEnv * sphereEnv * cloudShape * 1.75;
    // Outer 3D turquoise/violet star-nursery puffs extending into the sphere volume
    float outerPuff = smoothstep(0.52, 0.84, nBase) * fineFilaments * smoothstep(0.93, 0.42, r3) * smoothstep(0.28, 0.65, r3) * 1.05;
    float dens = mainCloud + outerPuff;

    // Rich, deep, high-contrast cosmic palette matching 04.png:
    vec3 colAbyss   = vec3(0.02, 0.04, 0.16);
    vec3 colIndigo  = vec3(0.14, 0.14, 0.62);
    vec3 colViolet  = vec3(0.42, 0.14, 0.84);
    vec3 colMagenta = vec3(0.98, 0.22, 0.54);
    vec3 colCoral   = vec3(1.00, 0.52, 0.32);
    vec3 colTurq    = vec3(0.06, 0.78, 0.98);
    vec3 colAqua    = vec3(0.30, 0.94, 1.00);
    vec3 colGold    = vec3(1.00, 0.82, 0.38);

    // Layered chromatic stratification across spiral arms, dust ridges, and lower/outer turquoise curls
    float magZone = clamp(smoothstep(0.32, 0.76, nWisp) * smoothstep(0.86, 0.12, r2) * (0.45 + 0.80 * arm2), 0.0, 1.0);
    float goldDust = smoothstep(0.42, 0.08, r2) * smoothstep(0.44, 0.82, nWisp) * (0.45 + 0.55 * arm2);
    float turqZone = clamp(
        smoothstep(-0.02, -0.68, pLocal.y / sphereR) * 0.92 +
        smoothstep(0.42, 0.88, r2) * smoothstep(0.42, 0.78, nBase) * 0.72,
        0.0, 1.0
    );

    vec3 nebCol = mix(colAbyss, colIndigo, smoothstep(0.18, 0.55, nBase));
    nebCol = mix(nebCol, colViolet, smoothstep(0.38, 0.74, nBase));
    nebCol = mix(nebCol, colMagenta, magZone);
    nebCol = mix(nebCol, colCoral, smoothstep(0.34, 0.09, r2) * magZone * 0.85);
    nebCol = mix(nebCol, colGold, goldDust * 0.85);
    nebCol = mix(nebCol, mix(colTurq, colAqua, fineFilaments), turqZone * (0.55 + 0.45 * nWisp));

    // Luminous rim highlights along wispy cloud ridges (starlight scattering on nebula edges)
    nebCol += mix(vec3(1.0, 0.55, 0.78), vec3(0.45, 0.92, 1.0), turqZone) * fineFilaments * 0.42;

    // Tight, radiant breathing golden star-nursery core
    float corePulse = 1.0 + 0.32 * breath;
    float coreHalo  = exp(-r3 * r3 * 72.0) * 1.15 * corePulse;
    float coreHot   = exp(-r3 * r3 * 340.0) * 2.80 * corePulse;

    // Volumetric golden core light rays radiating through the inner spiral arms
    float rayAngle = atan(qRot.y, qRot.x);
    float coreRays = pow(max(0.5 + 0.5 * cos(rayAngle * 6.0 + nBase * 2.0), 0.0), 4.0)
                   * exp(-r3 * 4.2) * diskEnv * 0.55 * corePulse;

    vec3 emission = nebCol * dens * (1.25 + 0.28 * breath)
                  + colGold * (coreHalo + coreRays)
                  + vec3(1.0, 0.96, 0.82) * coreHot;

    // Dark cosmic dust lanes absorb light behind them for dramatic 3D contrast
    float darkDust = smoothstep(0.56, 0.86, 1.0 - nBase) * diskEnv * smoothstep(0.90, 0.20, r3) * 1.15;

    // Dense 3D multi-scale pinpoint starfield embedded inside the rotating galaxy
    // Layer 1: bright jewel stars (grid 15)
    {
        vec3 cid = floor(qRot * 15.0);
        vec3 cf  = fract(qRot * 15.0) - 0.5;
        vec3 rnd = hash33(cid);
        if (rnd.x > 0.72 && r3 < 0.89) {
            vec3 spos = (rnd - 0.5) * 0.62;
            float dS = length(cf - spos);
            float tw = 0.45 + 0.55 * sin(TAU * phase * (1.0 + floor(rnd.y * 3.0)) + rnd.z * TAU);
            float star = smoothstep(0.085, 0.008, dS) * tw * smoothstep(0.91, 0.45, r3);
            vec3 sCol = mix(vec3(0.60, 0.86, 1.0), vec3(1.0, 0.86, 0.48), rnd.y);
            sCol = mix(sCol, vec3(1.0, 0.45, 0.76), step(0.74, rnd.z));
            emission += sCol * star * 3.8;
        }
    }
    // Layer 2: hundreds of crisp fine background star pinpoints (grid 28)
    {
        vec3 cid = floor(qRot * 28.0 + 7.3);
        vec3 cf  = fract(qRot * 28.0 + 7.3) - 0.5;
        vec3 rnd = hash33(cid);
        if (rnd.x > 0.66 && r3 < 0.91) {
            vec3 spos = (rnd - 0.5) * 0.65;
            float dS = length(cf - spos);
            float tw = 0.50 + 0.50 * sin(TAU * phase * (1.0 + floor(rnd.z * 2.0)) + rnd.y * TAU);
            float star = smoothstep(0.11, 0.015, dS) * tw * smoothstep(0.92, 0.50, r3);
            vec3 sCol = mix(vec3(0.75, 0.90, 1.0), vec3(1.0, 0.90, 0.68), rnd.y);
            emission += sCol * star * 2.2;
        }
    }

    return vec4(emission, dens + darkDust + coreHalo * 0.25);
}

// ---------------------------------------------------------------------------
// Ultra-Delicate Internal Golden Core Star Flare & Constellations
// ---------------------------------------------------------------------------
vec3 evalInternalFlares(vec3 ro, vec3 rd, vec3 center, float R, float phase, float breath) {
    vec3 oc = ro - center;
    float tClosest = max(0.0, -dot(oc, rd));
    vec3 pClose = oc + rd * tClosest;
    vec3 pNorm = pClose / R;
    float coreDist = length(pNorm.xy);

    float pulse = (1.0 + 0.30 * breath) * (1.0 + 0.14 * uOpen);
    vec3 goldLight = vec3(1.0, 0.86, 0.48);
    vec3 col = vec3(0.0);

    // Delicate gossamer golden star-cross rays from the core (razor-thin, NOT a thick X-blob!)
    float spikeV  = exp(-abs(pNorm.x) * 210.0) * exp(-abs(pNorm.y) * 2.4);
    float spikeH  = exp(-abs(pNorm.y) * 220.0) * exp(-abs(pNorm.x) * 3.2);
    float spikeD1 = exp(-abs(pNorm.x * 0.78 + pNorm.y * 0.62) * 240.0) * exp(-coreDist * 3.8);
    float spikeD2 = exp(-abs(pNorm.x * 0.62 - pNorm.y * 0.78) * 240.0) * exp(-coreDist * 4.2);

    col += goldLight * (spikeV * 0.55 + spikeH * 0.34 + spikeD1 * 0.24 + spikeD2 * 0.20) * pulse * smoothstep(0.88, 0.05, coreDist);

    // Tight incandescent star core pinpoint
    col += vec3(1.0, 0.94, 0.74) * exp(-coreDist * coreDist * 180.0) * 1.15 * pulse;

    // 5 crisp jeweled 4-point constellation stars inside the sphere
    vec2 nodes[5];
    nodes[0] = vec2( 0.00,  0.64);
    nodes[1] = vec2( 0.00, -0.58);
    nodes[2] = vec2( 0.34,  0.32);
    nodes[3] = vec2(-0.34, -0.34);
    nodes[4] = vec2( 0.56, -0.06);
    for (int i = 0; i < 5; i++) {
        vec2 d = pNorm.xy - nodes[i];
        float tw = 0.60 + 0.40 * sin(TAU * phase * 2.0 + float(i) * 1.55);
        float cDot = exp(-dot(d, d) * 1600.0);
        float cSpk = exp(-abs(d.x) * 150.0) * exp(-abs(d.y) * 18.0) +
                     exp(-abs(d.y) * 150.0) * exp(-abs(d.x) * 18.0);
        col += vec3(1.0, 0.94, 0.76) * (cDot * 1.4 + cSpk * 0.65) * tw * pulse;
    }

    return col;
}

// ---------------------------------------------------------------------------
// Shimmering Golden Stardust Particle Trails (Organic, Delicate, Zero Rigid Wires!)
// ---------------------------------------------------------------------------
vec4 evalStardustOrbit(
    vec3 ro, vec3 rd, vec3 center,
    vec3 nPlane, vec3 uAxis, vec3 vAxis,
    int ringKind, float phase, float breath,
    bool grayMode, out float tHit
) {
    tHit = 1e9;
    float denom = dot(rd, nPlane);
    if (abs(denom) < 0.0015) return vec4(0.0);

    float t = dot(center - ro, nPlane) / denom;
    if (t <= 0.05) return vec4(0.0);

    vec3 hitP = ro + rd * t - center;
    float u = dot(hitP, uAxis);
    float v = dot(hitP, vAxis);
    float r = length(vec2(u, v));
    float theta = atan(v, u);

    if (r < 1.12 || r > 2.48) return vec4(0.0);
    tHit = t;

    float rBreath = r / (1.0 + 0.032 * breath);
    float px = max(0.0028, t * 0.0014);

    vec3 col = vec3(0.0);
    float alpha = 0.0;
    vec3 goldCol = grayMode ? vec3(0.76) : vec3(1.0, 0.80, 0.38);
    vec3 starCol = grayMode ? vec3(0.95) : vec3(1.0, 0.95, 0.76);

    if (ringKind == 0) {
        // Ring System A: Ultra-delicate gossamer spun-starlight twin threads + drifting gold dust + 4-point jewels
        float orbitA = theta - TAU * phase;
        float uWrap = fract(orbitA / TAU);

        // Subtle organic wave along the delicate starlight threads
        float wave1 = 0.014 * sin(3.0 * orbitA);
        float wave2 = 0.014 * cos(2.0 * orbitA + 0.7);
        float d1 = abs(rBreath - (1.53 + wave1));
        float d2 = abs(rBreath - (1.62 + wave2));

        // Hairline gossamer filaments (modulated by sparkle gaps so they NEVER read as rigid solid wire!)
        float sparkleMod1 = 0.35 + 0.65 * pow(max(0.5 + 0.5 * sin(5.0 * orbitA + 0.4), 0.0), 1.4);
        float sparkleMod2 = 0.30 + 0.70 * pow(max(0.5 + 0.5 * sin(4.0 * orbitA + 2.1), 0.0), 1.5);
        float line1 = smoothstep(px * 1.4, px * 0.15, d1) * sparkleMod1;
        float line2 = smoothstep(px * 1.2, px * 0.15, d2) * sparkleMod2 * 0.72;
        float softGlow = (exp(-d1 * 38.0) * sparkleMod1 + exp(-d2 * 38.0) * sparkleMod2 * 0.7) * 0.16;

        // Fine sparkling stardust grains clinging to the gossamer threads
        float bandEnvA = exp(-sq((rBreath - 1.57) / 0.14));
        vec3 dustA = vec3(0.0);
        {
            float nAng = 110.0;
            float nRad = 18.0;
            float aCell = floor(uWrap * nAng);
            float rCell = floor((rBreath - 1.20) * nRad);
            vec2 fCell = vec2(fract(uWrap * nAng) - 0.5, fract((rBreath - 1.20) * nRad) - 0.5);
            float h1 = hash21(vec2(aCell, rCell + 11.0));
            float h2 = hash21(vec2(aCell + 23.1, rCell * 1.9 + 37.0));
            float h3 = hash21(vec2(aCell * 1.7, rCell + 71.3));
            if (h1 > 0.38) {
                vec2 dd = fCell - (vec2(h2, h3) - 0.5) * 0.55;
                dd.x *= (TAU * rBreath / nAng) / (1.0 / nRad);
                float dist = length(dd);
                float tw = 0.45 + 0.55 * sin(TAU * phase * (1.0 + floor(h3 * 3.0)) + h2 * TAU);
                float sp = smoothstep(mix(0.08, 0.19, h1 * h2), 0.008, dist) * tw * bandEnvA;
                dustA += mix(goldCol, starCol, h2) * sp * 1.9;
            }
        }

        col += goldCol * (line1 * 0.85 + line2 * 0.65 + softGlow * (grayMode ? 0.15 : 0.75)) + dustA;
        alpha = clamp((line1 + line2) * 0.75 + softGlow + length(dustA) * 0.4, 0.0, 1.0);

        // 5 orbiting razor-sharp 4-point diamond star nodes
        for (int i = 0; i < 5; i++) {
            float fi = float(i);
            float angTarget = fi * TAU / 5.0 + 0.35;
            float dAng = atan(sin(orbitA - angTarget), cos(orbitA - angTarget));
            float arcD = dAng * 1.58;
            float radD = rBreath - mix(1.53, 1.62, mod(fi, 2.0));

            float core = exp(-(sq(arcD) + sq(radD)) * 1100.0);
            float cross1 = exp(-abs(arcD) * 85.0) * exp(-abs(radD) * 13.0);
            float cross2 = exp(-abs(radD) * 85.0) * exp(-abs(arcD) * 13.0);
            float tw = 0.65 + 0.35 * sin(TAU * phase * 2.0 + fi * 1.7);
            float starVal = (core * 2.4 + (cross1 + cross2) * 1.05) * tw;

            col += starCol * starVal * (grayMode ? 0.50 : 1.55);
            alpha = max(alpha, clamp(starVal * 0.7, 0.0, 1.0));
        }
    } else {
        // Ring System B: Lush, shimmering celestial stardust particle river (3 braided dust layers!)
        float thetaAnim = theta + TAU * phase;
        float uWrap = fract(thetaAnim / TAU);

        // Gentle braided stream offset so the stardust belt flows organically
        float braid = 0.055 * sin(3.0 * thetaAnim) + 0.025 * cos(5.0 * thetaAnim);
        float rCenter = 1.80 + braid;
        float bandEnv = exp(-sq((rBreath - rCenter) / 0.24));

        // Ultra-faint gossamer shimmer thread buried inside the stardust river (visible cleanly in grayMode)
        float dThread = abs(rBreath - rCenter);
        float thread = smoothstep(px * 1.4, px * 0.15, dThread) * (grayMode ? 0.75 : 0.32);

        // 3 dense multi-scale polar stardust layers (2x2-safe clamped particle margins = zero cell clipping!)
        vec3 dustCol = vec3(0.0);
        for (int layer = 0; layer < 3; layer++) {
            float fl = float(layer);
            float nAng = (layer == 0) ? 72.0 : ((layer == 1) ? 132.0 : 210.0);
            float nRad = (layer == 0) ? 11.0 : ((layer == 1) ? 18.0  : 26.0);
            // Slight phase offset between layers for lush braided depth
            float uShift = fract(uWrap + fl * 0.137);
            float aCell = floor(uShift * nAng);
            float rCell = floor((rBreath - 1.15) * nRad);
            vec2 fCell = vec2(fract(uShift * nAng) - 0.5, fract((rBreath - 1.15) * nRad) - 0.5);

            float h1 = hash21(vec2(aCell, rCell + fl * 47.0));
            float h2 = hash21(vec2(aCell + 19.3, rCell * 1.7 + fl * 91.0));
            float h3 = hash21(vec2(aCell * 2.1, rCell + 53.7 + fl * 13.0));

            float thresh = (layer == 0) ? 0.30 : ((layer == 1) ? 0.24 : 0.22);
            if (h1 > thresh) {
                vec2 offset = (vec2(h2, h3) - 0.5) * 0.52;
                vec2 dd = fCell - offset;
                dd.x *= (TAU * rBreath / nAng) / (1.0 / nRad);
                float dist = length(dd);
                float size = (layer == 0) ? mix(0.10, 0.22, h1 * h2)
                           : ((layer == 1) ? mix(0.07, 0.16, h1 * h2)
                                           : mix(0.05, 0.12, h1 * h2));
                float tw = 0.42 + 0.58 * sin(TAU * phase * (1.0 + floor(h3 * 3.0)) + h2 * TAU);
                float spark = smoothstep(size, 0.008, dist) * tw * bandEnv;

                vec3 pCol = goldCol;
                if (!grayMode) {
                    if (h3 > 0.80)      pCol = vec3(0.42, 0.85, 1.0);
                    else if (h3 > 0.66) pCol = vec3(0.98, 0.45, 0.82);
                    else if (h2 > 0.68) pCol = vec3(1.0, 0.96, 0.82);
                }
                float boost = (layer == 0) ? 2.4 : ((layer == 1) ? 1.65 : 1.15);
                dustCol += pCol * spark * boost;
            }
        }

        // Ethereal stardust mist ribbon
        float mistWave = 0.5 + 0.5 * sin(uWrap * TAU * 4.0 + rBreath * 6.0);
        vec3 mist = mix(goldCol, vec3(0.55, 0.72, 1.0), grayMode ? 0.0 : 0.25)
                  * bandEnv * (0.045 + 0.045 * mistWave) * (grayMode ? 0.30 : 0.72);

        // 5 bright orbiting 4-point star flares along the stardust river
        for (int i = 0; i < 5; i++) {
            float fi = float(i);
            float angTarget = fi * TAU / 5.0 + 0.65;
            float dAng = atan(sin(thetaAnim - angTarget), cos(thetaAnim - angTarget));
            float arcD = dAng * 1.80;
            float radD = rBreath - (rCenter + 0.06 * sin(fi * 2.3));
            float core = exp(-(sq(arcD) + sq(radD)) * 950.0);
            float flare = exp(-abs(arcD) * 76.0) * exp(-abs(radD) * 12.0) +
                          exp(-abs(radD) * 76.0) * exp(-abs(arcD) * 12.0);
            float tw = 0.62 + 0.38 * sin(TAU * phase * 2.0 + fi * 2.1);
            dustCol += starCol * (core * 2.4 + flare * 0.95) * tw * (grayMode ? 0.45 : 1.55);
        }

        col += goldCol * thread + mist + dustCol;
        alpha = clamp(thread * 0.75 + bandEnv * 0.22 + length(dustCol) * 0.42, 0.0, 1.0);
    }

    return vec4(col, alpha);
}

// ---------------------------------------------------------------------------
// Subtle Overhead Temple God-Rays & Floating Cosmic Motes (Seamless 3.0s)
// ---------------------------------------------------------------------------
vec3 evalTempleAtmosphere(vec2 uv, float phase, float breath, bool grayMode) {
    vec3 col = vec3(0.0);

    // Soft overhead volumetric light shafts descending from temple oculus onto orb
    if (uv.y > -0.10) {
        vec2 oculus = vec2(0.0, 1.35);
        vec2 d = uv - oculus;
        float ang = atan(d.x, -d.y);
        float dist = length(d);

        float sway = 0.026 * sin(TAU * phase);
        float shaft = 0.0;
        shaft += exp(-sq((ang - (-0.42 + sway)) * 8.5)) * 0.60;
        shaft += exp(-sq((ang - (-0.18 - sway * 0.7)) * 9.5)) * 0.85;
        shaft += exp(-sq((ang - ( 0.02 + sway * 0.5)) * 7.8)) * 1.00;
        shaft += exp(-sq((ang - ( 0.24 - sway * 0.8)) * 9.0)) * 0.72;
        shaft += exp(-sq((ang - ( 0.46 + sway * 0.6)) * 8.5)) * 0.52;

        float fade = smoothstep(1.80, 0.30, dist) * smoothstep(-0.10, 0.30, uv.y);
        vec3 rayCol = grayMode ? vec3(0.05) : vec3(0.14, 0.22, 0.38);
        col += rayCol * shaft * fade * (0.28 + 0.06 * breath);
    }

    // Crisp floating cosmic motes in the dark temple air
    if (!grayMode) {
        for (int i = 0; i < 10; i++) {
            float fi = float(i);
            float sx = (hash11(fi * 17.3 + 1.1) - 0.5) * 2.2;
            float sy = (hash11(fi * 29.7 + 4.2) - 0.5) * 1.5;
            vec2 pos = vec2(
                sx + 0.07 * cos(TAU * phase + fi * 1.9),
                sy + 0.05 * sin(TAU * phase + fi * 2.3)
            );
            float r = length(uv - pos);
            float tw = 0.50 + 0.50 * sin(TAU * phase * 2.0 + fi * 3.1);
            float mote = exp(-r * r * 4200.0) * tw;
            vec3 mCol = (mod(fi, 3.0) < 1.0) ? vec3(1.0, 0.62, 0.38) :
                        (mod(fi, 3.0) < 2.0) ? vec3(0.48, 0.74, 1.0) :
                                               vec3(1.0, 0.38, 0.56);
            col += mCol * mote * 0.62;
        }
    }

    return col;
}

// ---------------------------------------------------------------------------
// ACES Filmic Tonemapping with gentle peak headroom (%clip < 1%)
// ---------------------------------------------------------------------------
vec3 acesFilm(vec3 x) {
    const float a = 2.51;
    const float b = 0.03;
    const float c = 2.43;
    const float d = 0.59;
    const float e = 0.14;
    vec3 mapped = clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0);
    return mapped * 0.965;
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution) / uResolution.y;

    // Seamless 3.0s animation phase
    float phase  = fract(uTime / 3.0);
    float breath = sin(TAU * phase);

    bool grayMode = (uLightMode == 1);

    // Sphere transform (gently levitating & breathing)
    vec3 sphereC = vec3(0.0, 0.36 + 0.045 * breath, 0.0);
    float sphereR = 1.02 * (1.0 + 0.025 * breath);

    // Camera setup:
    // uCamMode 0 = Hero framing (full orb + full twin stardust rings + full carved pedestal + headroom)
    // uCamMode 1 = ~2.5x Macro close-up inside refractive glass orb & swirling volumetric nebula core
    vec3 ro, ta;
    float focal;
    if (uCamMode == 1) {
        ro = vec3(0.08, 0.38 + 0.02 * breath, 2.70);
        ta = vec3(0.0,  0.35 + 0.02 * breath, 0.0);
        focal = 1.82;
    } else {
        ro = vec3(0.0, 0.24, 6.40);
        ta = vec3(0.0, -0.18, 0.0);
        focal = 1.66;
    }

    vec3 ww = normalize(ta - ro);
    vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0)));
    vec3 vv = cross(uu, ww);
    vec3 rd = normalize(uv.x * uu + uv.y * vv + focal * ww);

    // Lighting rig by uLightMode
    vec3 keyDir, keyCol, fillCol, rimDir, rimCol;
    if (uLightMode == 1) {
        keyDir  = normalize(vec3(0.58, 0.72, 0.42));
        keyCol  = vec3(0.85);
        fillCol = vec3(0.07);
        rimDir  = normalize(vec3(-0.65, 0.48, -0.60));
        rimCol  = vec3(0.55);
    } else if (uLightMode == 2) {
        keyDir  = normalize(vec3(0.94, 0.20, 0.28));
        keyCol  = vec3(1.10, 0.88, 0.68);
        fillCol = vec3(0.018, 0.024, 0.045);
        rimDir  = normalize(vec3(-0.85, 0.30, -0.42));
        rimCol  = vec3(0.28, 0.48, 0.88);
    } else if (uLightMode == 3) {
        keyDir  = normalize(vec3(0.14, 0.50, -0.85));
        keyCol  = vec3(1.15, 0.85, 0.62);
        fillCol = vec3(0.014, 0.020, 0.040);
        rimDir  = normalize(vec3(-0.20, 0.45, -0.87));
        rimCol  = vec3(0.65, 0.82, 1.25);
    } else {
        keyDir  = normalize(vec3(0.16, 0.92, 0.36));
        keyCol  = vec3(0.40, 0.52, 0.78);
        fillCol = vec3(0.022, 0.030, 0.056);
        rimDir  = normalize(vec3(-0.45, 0.65, -0.60));
        rimCol  = vec3(0.32, 0.44, 0.76);
    }

    // -----------------------------------------------------------------------
    // 1. Raymarch Solid Scene (Carved Stone Pedestal + Temple Chamber)
    // -----------------------------------------------------------------------
    float tScene = 0.0;
    float matId  = -1.0;
    const float MAX_DIST = 16.0;
    for (int i = 0; i < 56; i++) {
        vec3 p = ro + rd * tScene;
        vec2 h = mapScene(p);
        if (h.x < 0.0022) {
            matId = h.y;
            break;
        }
        tScene += h.x;
        if (tScene > MAX_DIST) {
            tScene = MAX_DIST;
            break;
        }
    }

    // Deep moody temple backdrop (lumMin ~7-12, %black == 0%)
    float bgGrad = clamp(0.5 + 0.5 * rd.y, 0.0, 1.0);
    vec3 col = grayMode
        ? mix(vec3(0.018), vec3(0.048), bgGrad)
        : mix(vec3(0.0022, 0.0030, 0.0068), vec3(0.0072, 0.0108, 0.0220), bgGrad);

    if (matId < 0.0 && rd.y > 0.02) {
        float archRib = 0.5 + 0.5 * sin(atan(rd.z, rd.x) * 18.0);
        col += (grayMode ? vec3(0.012) : vec3(0.004, 0.006, 0.012)) * archRib * smoothstep(0.02, 0.45, rd.y);
    }

    if (matId > 0.0) {
        vec3 p = ro + rd * tScene;
        vec3 N = calcNormal(p);
        float ao = calcAO(p, N);
        float sh = calcSoftShadow(p + N * 0.015, keyDir, 0.05, 6.0);

        vec3 albedo;
        float rough;
        if (matId < 1.5) {
            float stoneN = fbmStone(p * 3.8);
            float fineN  = vnoise3(p * 15.0);
            albedo = grayMode
                ? mix(vec3(0.16), vec3(0.32), stoneN * 0.7 + fineN * 0.3)
                : mix(vec3(0.040, 0.050, 0.076), vec3(0.112, 0.135, 0.182), stoneN * 0.7 + fineN * 0.3);
            float rimDust = smoothstep(-0.76, -0.67, p.y) * smoothstep(0.75, 1.28, length(p.xz));
            albedo += (grayMode ? vec3(0.12) : vec3(0.068, 0.082, 0.118)) * rimDust;
            rough = 0.56;
        } else if (matId < 2.5) {
            float rFloor = length(p.xz);
            float angFloor = atan(p.z, p.x);
            float tileRing = smoothstep(0.04, 0.01, abs(fract(rFloor * 0.55) - 0.5));
            float tileRad  = smoothstep(0.025, 0.005, abs(fract(angFloor * 12.0 / TAU) - 0.5));
            float tileSeam = max(tileRing, tileRad * smoothstep(1.2, 2.0, rFloor));
            float marble   = fbmStone(vec3(p.xz * 1.2, 0.5));
            albedo = grayMode
                ? mix(vec3(0.10), vec3(0.20), marble) * (1.0 - 0.42 * tileSeam)
                : mix(vec3(0.022, 0.032, 0.052), vec3(0.085, 0.112, 0.155), marble) * (1.0 - 0.48 * tileSeam);
            rough = 0.40;
        } else {
            float wallN = vnoise3(p * 2.2);
            albedo = grayMode
                ? mix(vec3(0.06), vec3(0.12), wallN)
                : mix(vec3(0.012, 0.018, 0.034), vec3(0.038, 0.052, 0.082), wallN);
            rough = 0.78;
        }

        float diff = max(dot(N, keyDir), 0.0) * sh;
        vec3 H = normalize(keyDir - rd);
        float spec = pow(max(dot(N, H), 0.0), mix(48.0, 10.0, rough)) * sh;
        float rim  = pow(max(1.0 - max(dot(N, -rd), 0.0), 0.0), 3.0) * max(dot(N, rimDir) * 0.5 + 0.5, 0.0);

        vec3 lit = albedo * (fillCol * ao + keyCol * diff) + keyCol * spec * 0.22 + rimCol * rim * 0.24 * ao;

        // Focused cosmic bounce light cast by the hovering nebula sphere
        vec3 toOrb = sphereC - p;
        float dOrb = length(toOrb);
        vec3 lOrb  = toOrb / max(dOrb, 0.001);
        float orbDiff = max(dot(N, lOrb), 0.0);
        float orbAtten = 1.0 / (0.55 + dOrb * dOrb * 1.15);
        float orbPulse = 1.0 + 0.25 * breath;

        vec3 orbLightCol = grayMode
            ? vec3(0.14)
            : mix(vec3(0.30, 0.62, 0.98), vec3(0.78, 0.24, 0.52), smoothstep(0.35, 1.15, length(p.xz)));
        lit += albedo * orbLightCol * orbDiff * orbAtten * 1.25 * orbPulse;

        // Focused cyan-violet-rose caustic reflection right beneath the hovering orb on the pedestal slab
        if (matId < 1.5 && p.y > -0.74) {
            float rTop = length(p.xz);
            float contactGlow = exp(-rTop * rTop * 7.0) * orbPulse;
            float causticPool = exp(-sq((rTop - 0.58) * 3.4)) * (0.5 + 0.5 * sin(atan(p.z, p.x) * 5.0 - TAU * phase));
            vec3 cCol = grayMode
                ? vec3(0.20) * contactGlow
                : vec3(0.36, 0.76, 1.0) * contactGlow * 0.68 + vec3(0.66, 0.18, 0.36) * causticPool * 0.24;
            lit += cCol;
        }

        float fog = 1.0 - exp(-tScene * tScene * 0.011);
        vec3 fogCol = grayMode ? vec3(0.025) : vec3(0.0035, 0.0050, 0.0110);
        col = mix(lit, fogCol, fog);
    }

    // -----------------------------------------------------------------------
    // 2. Evaluate Shimmering Tilted Stardust Orbits (Exact 3D Depth)
    // -----------------------------------------------------------------------
    vec3 nA = normalize(vec3(0.29, 0.88, 0.37));
    vec3 uA = normalize(cross(vec3(0.0, 0.0, 1.0), nA));
    vec3 vA = cross(nA, uA);
    float tRingA;
    vec4 ringA = evalStardustOrbit(ro, rd, sphereC, nA, uA, vA, 0, phase, breath, grayMode, tRingA);
    if (tRingA > tScene) ringA = vec4(0.0);

    vec3 nB = normalize(vec3(-0.27, 0.90, 0.34));
    vec3 uB = normalize(cross(vec3(0.0, 0.0, 1.0), nB));
    vec3 vB = cross(nB, uB);
    float tRingB;
    vec4 ringB = evalStardustOrbit(ro, rd, sphereC, nB, uB, vB, 1, phase, breath, grayMode, tRingB);
    if (tRingB > tScene) ringB = vec4(0.0);

    // -----------------------------------------------------------------------
    // 3. Analytical Glass Sphere Intersection & Crisp 36-Step Nebula Raymarch
    // -----------------------------------------------------------------------
    vec2 sphHit = iSphere(ro - sphereC, rd, sphereR);
    bool hitSphere = (sphHit.x > 0.0 && sphHit.x < tScene);

    // Composite stardust orbits BEHIND the sphere first
    if (ringA.a > 0.001 && (!hitSphere || tRingA > sphHit.x)) {
        col = mix(col, col + ringA.rgb, ringA.a);
    }
    if (ringB.a > 0.001 && (!hitSphere || tRingB > sphHit.x)) {
        col = mix(col, col + ringB.rgb, ringB.a);
    }

    // Render Refractive Crystal Glass Sphere + Deep Multi-Octave Swirling Nebula
    if (hitSphere) {
        vec3 pFront = ro + rd * sphHit.x;
        vec3 N = normalize(pFront - sphereC);
        float ndv = clamp(dot(N, -rd), 0.0, 1.0);

        // Refracted ray entering the crystal sphere (IOR = 1.46)
        vec3 rdIn = refract(rd, N, 1.0 / 1.46);
        vec2 innerHit = iSphere(pFront - sphereC, rdIn, sphereR);
        float chordLen = max(innerHit.y, 0.05);

        // Deep cosmic midnight-navy backdrop inside crystal orb
        vec3 bgThrough = grayMode
            ? col * vec3(0.62)
            : mix(vec3(0.005, 0.008, 0.026), col * vec3(0.22, 0.28, 0.50), 0.30);

        // 36-step volumetric raymarch with 5-octave gyroid nebula
        const int NEB_STEPS = 36;
        float dt = chordLen / float(NEB_STEPS);
        float jitter = hash21(gl_FragCoord.xy) * 0.55;
        vec3 nebAccum = vec3(0.0);
        float trans = 1.0;

        for (int i = 0; i < NEB_STEPS; i++) {
            float tStep = (float(i) + 0.15 + jitter * 0.5) * dt;
            vec3 pSample = (pFront - sphereC) + rdIn * tStep;
            vec4 s = sampleNebula(pSample, phase, breath, sphereR);
            if (s.a > 0.001) {
                float stepAlpha = 1.0 - exp(-s.a * dt * 2.15);
                nebAccum += trans * s.rgb * dt * 0.96;
                trans *= (1.0 - stepAlpha * 0.74);
                if (trans < 0.03) break;
            }
        }

        // Delicate internal golden star-core rays & jeweled constellation stars
        vec3 flares = evalInternalFlares(pFront, rdIn, sphereC, sphereR, phase, breath);

        vec3 interior;
        if (grayMode) {
            float nebLuma = dot(nebAccum + flares * 0.22, vec3(0.299, 0.587, 0.114));
            interior = bgThrough * trans + vec3(0.04) * (1.0 - trans) + vec3(nebLuma * 0.20);
        } else {
            vec3 deepVoid = vec3(0.006, 0.010, 0.036) * (1.0 - trans);
            interior = bgThrough * trans + deepVoid + nebAccum + flares;
        }

        // Crystal-clear glass shell Fresnel & razor-sharp speculars (zero milky oval!)
        float fresnel = 0.02 + 0.98 * pow(max(1.0 - ndv, 0.0), 4.4);

        vec3 R = reflect(rd, N);
        // Sharp curved crescent highlight tightly hugging the top glass crown (like 04.png!)
        float topCrown = smoothstep(0.76, 0.94, N.y) * smoothstep(0.62, 0.88, dot(R, normalize(vec3(0.04, 0.94, 0.34))));
        float keySpec  = pow(max(dot(R, keyDir), 0.0), 64.0);
        float rimSpec  = pow(max(dot(R, rimDir), 0.0), 26.0);

        // Crisp cyan-aqua caustic crescent at the bottom contact rim
        float botCaustic = smoothstep(-0.74, -0.97, N.y) * (0.65 + 0.35 * pow(max(1.0 - ndv, 0.0), 1.5));

        vec3 fresCol;
        if (grayMode) {
            fresCol = vec3(0.86);
        } else {
            fresCol = mix(vec3(0.32, 0.70, 1.0), vec3(0.86, 0.56, 1.0), smoothstep(-0.4, 0.65, N.y));
            fresCol += vec3(0.10, 0.16, 0.26) * (0.5 + 0.5 * breath);
        }

        vec3 glassCol = interior;
        glassCol += fresCol * fresnel * (grayMode ? 0.92 : 0.98);
        glassCol += (grayMode ? vec3(0.90) : vec3(0.92, 0.88, 1.0)) * topCrown * (grayMode ? 0.68 : 0.76);
        glassCol += keyCol * keySpec * (grayMode ? 0.70 : 0.62);
        glassCol += rimCol * rimSpec * (uLightMode == 3 ? 1.15 : 0.42);
        glassCol += (grayMode ? vec3(0.45) : vec3(0.38, 0.86, 1.0)) * botCaustic * (0.72 + 0.22 * breath);

        float edgeAA = smoothstep(0.0, 0.05, ndv);
        col = mix(col, glassCol, edgeAA);
    }

    // -----------------------------------------------------------------------
    // 4. Composite Stardust Orbits IN FRONT of the Sphere
    // -----------------------------------------------------------------------
    if (ringA.a > 0.001 && hitSphere && tRingA <= sphHit.x) {
        col = mix(col, col + ringA.rgb, ringA.a);
    }
    if (ringB.a > 0.001 && hitSphere && tRingB <= sphHit.x) {
        col = mix(col, col + ringB.rgb, ringB.a);
    }

    // -----------------------------------------------------------------------
    // 5. Temple God-Rays, Subtle Outer Halo & Floating Motes
    // -----------------------------------------------------------------------
    if (uCamMode == 0) {
        col += evalTempleAtmosphere(uv, phase, breath, grayMode);

        if (!grayMode) {
            vec3 oc = ro - sphereC;
            float b = dot(oc, rd);
            float dRay = length(oc - rd * b);
            float halo = exp(-max(dRay - sphereR * 0.98, 0.0) * 6.8) * (0.11 + 0.04 * breath);
            col += vec3(0.24, 0.36, 0.78) * halo * smoothstep(sphereR * 0.75, sphereR * 1.03, dRay);
        }
    }

    // Subtle cosmic ambient floor so lumMin >= 6 and %black == 0% without milky haze
    if (grayMode) {
        col = max(col, vec3(0.004));
    } else {
        col = max(col, vec3(0.0012, 0.0016, 0.0032));
    }

    // ACES filmic tonemapping + sRGB gamma
    col = acesFilm(col);
    col = pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2));

    // Guarantee pure neutral grayscale R == G == B in uLightMode == 1
    if (grayMode) {
        float g = dot(col, vec3(0.299, 0.587, 0.114));
        col = vec3(g);
    }

    fragColor = vec4(col, 1.0);
}
