#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;

// ============================================================================
// 10_arcane_portal_rift_vortex.glsl
// Vertical standing elliptical arcane space-time portal hovering above a dark
// wet tiled obsidian arena floor: incandescent white-gold event-horizon ring,
// orbiting arcane runes & golden stardust, deep swirling cyan-cobalt vortex
// into a starry void core, and luminous golden-cyan mirror floor reflection.
// ============================================================================

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

// Unified Arcane Palette (Locked)
const vec3 COL_OBSIDIAN   = vec3(0.03, 0.05, 0.12);
const vec3 COL_COBALT     = vec3(0.08, 0.32, 0.98);
const vec3 COL_CYAN       = vec3(0.10, 0.85, 1.00);
const vec3 COL_GOLD       = vec3(1.00, 0.68, 0.18);
const vec3 COL_WHITE_GOLD = vec3(1.00, 0.96, 0.86);

const vec3 PORTAL_CENTER  = vec3(0.0, 1.38, 0.0);

// ----------------------------------------------------------------------------
// Hash & Procedural Noise
// ----------------------------------------------------------------------------
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);
}

vec2 hash22(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.xx + p3.yz) * p3.zy);
}

mat2 rot2(float a) {
    float c = cos(a), s = sin(a);
    return mat2(c, -s, s, c);
}

float vnoise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    float a = hash21(i);
    float b = hash21(i + vec2(1.0, 0.0));
    float c = hash21(i + vec2(0.0, 1.0));
    float d = hash21(i + vec2(1.0, 1.0));
    return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

float fbm4(vec2 p) {
    float v = 0.0;
    float a = 0.5;
    mat2 m = mat2(0.80, -0.60, 0.60, 0.80);
    for (int i = 0; i < 4; i++) {
        v += a * vnoise(p);
        p = m * p * 2.03 + vec2(17.1, 31.7);
        a *= 0.5;
    }
    return v;
}

// ----------------------------------------------------------------------------
// 2D SDF Primitives for Arcane Runes
// ----------------------------------------------------------------------------
float sdSeg(vec2 p, vec2 a, vec2 b) {
    vec2 pa = p - a, ba = b - a;
    float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0);
    return length(pa - ba * h);
}

float sdRune(vec2 p, int id) {
    float d = 1e5;
    if (id == 0) {
        // Hourglass / Gemini sigil (signature rune from reference)
        vec2 q = abs(p);
        float curveX = 0.24 - 0.12 * cos(clamp(p.y * 3.4, -PI, PI));
        d = min(d, abs(q.x - curveX) + max(q.y - 0.44, 0.0));
        d = min(d, sdSeg(p, vec2(-0.30,  0.42), vec2(0.30,  0.42)));
        d = min(d, sdSeg(p, vec2(-0.30, -0.42), vec2(0.30, -0.42)));
        d = min(d, sdSeg(p, vec2(-0.14,  0.00), vec2(0.14,  0.00)));
    } else if (id == 1) {
        // Concave 4-point arcane diamond + inner cross
        vec2 q = abs(p);
        float dia = (q.x + q.y) * 0.7071 - 0.34;
        float pinch = -0.10 * exp(-length(q - vec2(0.22)) * 5.0);
        d = min(d, abs(dia + pinch));
        d = min(d, sdSeg(p, vec2(0.0, -0.24), vec2(0.0, 0.24)));
        d = min(d, sdSeg(p, vec2(-0.24, 0.0), vec2(0.24, 0.0)));
    } else if (id == 2) {
        // Arcane ring-crescent glyph
        d = min(d, abs(length(p) - 0.30));
        d = min(d, sdSeg(p, vec2(-0.24, -0.34), vec2(0.24, 0.34)));
        d = min(d, sdSeg(p, vec2(-0.28,  0.14), vec2(0.28, 0.14)));
        d = min(d, abs(length(p - vec2(0.0, -0.08)) - 0.11));
    } else {
        // Double-chevron / rune pillar
        vec2 q = abs(p);
        d = min(d, sdSeg(vec2(q.x, p.y), vec2(0.26,  0.42), vec2(0.08,  0.0)));
        d = min(d, sdSeg(vec2(q.x, p.y), vec2(0.08,  0.0),  vec2(0.26, -0.42)));
        d = min(d, sdSeg(p, vec2(-0.24,  0.34), vec2(0.24,  0.34)));
        d = min(d, sdSeg(p, vec2(-0.24, -0.34), vec2(0.24, -0.34)));
        d = min(d, length(p) - 0.055);
    }
    return d;
}

// ----------------------------------------------------------------------------
// Portal Geometry Helpers
// ----------------------------------------------------------------------------
vec2 getPortalAxes(float openAmt) {
    float o = smoothstep(0.0, 1.0, clamp(openAmt, 0.0, 1.0));
    return vec2(mix(0.46, 0.66, o), mix(0.92, 1.12, o));
}

vec3 getPortalCenter(vec2 ab) {
    return vec3(0.0, ab.y + 0.09, 0.0);
}

// IQ gradient-normalized signed Euclidean distance to axis-aligned ellipse
float sdEllipseApprox(vec2 p, vec2 ab) {
    vec2 q = p / max(ab, vec2(1e-4));
    float eR = length(q);
    vec2 g = q / max(ab, vec2(1e-4));
    return eR * (eR - 1.0) / max(length(g), 1e-4);
}

// ----------------------------------------------------------------------------
// Wet Tiled Obsidian Floor Surface & SDF
// ----------------------------------------------------------------------------
struct FloorInfo {
    float height;
    float grout;
    float wet;
    float tileId;
};

FloorInfo sampleFloor(vec2 xz) {
    // Diagonal tile orientation matching cinematic 3/4 view
    vec2 p = rot2(0.54) * xz;
    float tileSize = 0.82;
    vec2 tp = p / tileSize;
    vec2 id = floor(tp);
    vec2 f = fract(tp) - 0.5;
    float tid = hash21(id);

    // Grout seam & beveled tile edge
    vec2 edgeDist = 0.5 - abs(f);
    float minEdge = min(edgeDist.x, edgeDist.y);
    float groutMask = 1.0 - smoothstep(0.012, 0.036, minEdge);
    float bevel = smoothstep(0.014, 0.075, minEdge);

    // Procedural stone relief & wet puddles
    float macroNoise = fbm4(xz * 0.72 + vec2(3.4, -1.9));
    float microStone = fbm4(p * 3.6 + vec2(tid * 13.7, tid * 7.3));
    float finePits = vnoise(p * 18.0 + tid * 5.0);

    // Puddle wetness: smooth pools on tiles + higher wetness near portal center
    float puddle = smoothstep(0.36, 0.66, macroNoise + 0.14 * (tid - 0.5));
    float centerWet = exp(-dot(xz, xz) * 0.14) * 0.25;
    float wet = clamp(0.26 + 0.68 * puddle + centerWet, 0.18, 0.96);
    wet *= (1.0 - 0.65 * groutMask);

    // Flatten stone micro-bump slightly inside mirror puddles
    float bumpAmp = mix(0.014, 0.0032, wet);
    float tileOffset = (tid - 0.5) * 0.004;
    float h = tileOffset + (microStone - 0.5) * bumpAmp + (finePits - 0.5) * bumpAmp * 0.35;
    h *= bevel;
    h -= groutMask * 0.018;

    FloorInfo fi;
    fi.height = h;
    fi.grout = groutMask;
    fi.wet = wet;
    fi.tileId = tid;
    return fi;
}

float mapFloor(vec3 p) {
    return p.y - sampleFloor(p.xz).height;
}

// 3D Scene SDF (used for clay mode & 3D portal ring geometry)
float mapClay(vec3 p, vec2 ab, out int matId) {
    float dFloor = mapFloor(p);
    vec3 pCenter = getPortalCenter(ab);
    vec2 lp = p.xy - pCenter.xy;
    float dEll = sdEllipseApprox(lp, ab);
    float dRing = length(vec2(dEll, p.z)) - 0.055;
    // Recessed vortex dish inside ellipse
    float eR = length(lp / max(ab, vec2(1e-4)));
    float dishZ = -0.22 * max(0.0, 1.0 - eR * eR);
    float dDish = max(abs(p.z - dishZ) - 0.018, dEll - 0.01);

    float d = dFloor;
    matId = 0;
    if (dRing < d) { d = dRing; matId = 1; }
    if (dDish < d) { d = dDish; matId = 2; }
    return d;
}

// Unit-weight tetrahedral normals (QA contract: const vec2 k = vec2(1., -1.))
vec3 calcFloorNormal(vec3 p) {
    const vec2 k = vec2(1.0, -1.0);
    const float h = 0.0035;
    return normalize(
        k.xyy * mapFloor(p + k.xyy * h) +
        k.yyx * mapFloor(p + k.yyx * h) +
        k.yxy * mapFloor(p + k.yxy * h) +
        k.xxx * mapFloor(p + k.xxx * h)
    );
}

vec3 calcClayNormal(vec3 p, vec2 ab) {
    const vec2 k = vec2(1.0, -1.0);
    const float h = 0.0025;
    int m;
    return normalize(
        k.xyy * mapClay(p + k.xyy * h, ab, m) +
        k.yyx * mapClay(p + k.yyx * h, ab, m) +
        k.yxy * mapClay(p + k.yxy * h, ab, m) +
        k.xxx * mapClay(p + k.xxx * h, ab, m)
    );
}

// ----------------------------------------------------------------------------
// Sparkling Golden Stardust (Seamless 3s loop via phase = uTime * TAU / 3.0)
// ----------------------------------------------------------------------------
vec3 evalRimSparks(vec2 lp, vec2 ab, float dEll, float phase, float openAmt) {
    // Only evaluate near the portal rim band
    if (dEll < -0.14 || dEll > 0.34) return vec3(0.0);

    vec2 q = lp / max(ab, vec2(1e-4));
    float ang = atan(q.y, q.x); // -PI..PI

    vec3 acc = vec3(0.0);

    // 3 concentric orbital dust layers with integer harmonic angular speeds
    for (int layer = 0; layer < 3; layer++) {
        float fl = float(layer);
        float sectors = 36.0 + fl * 18.0; // 36, 54, 72
        float orbitSpeed = (layer == 1) ? -1.0 : 1.0;
        // Seamless loop: shifting angle by integer * TAU / sectors or full TAU
        float shiftedAng = ang - phase * orbitSpeed * (2.0 / sectors) * 6.0;
        float u = (shiftedAng + PI) / TAU * sectors;
        float cell = floor(u);
        float fu = fract(u) - 0.5;

        // Check neighbor cells to prevent clipping across sector boundaries
        for (int s = -1; s <= 1; s++) {
            float cid = mod(cell + float(s) + sectors, sectors);
            vec2 h = hash22(vec2(cid + fl * 91.7, fl * 17.3 + 5.1));
            float h2 = hash21(vec2(cid * 3.1, fl * 29.4));

            // Radial spread around outer rim
            float rSpread = mix(-0.03, 0.20 + fl * 0.04, h.y * h.y);
            // Gentle radial breathe
            rSpread += 0.015 * sin(phase * 2.0 + h.x * TAU);

            float du = (fu - float(s) - (h.x - 0.5) * 0.72) * (TAU / sectors) * length(ab) * 0.65;
            float dv = dEll - rSpread;
            float dist = length(vec2(du, dv));

            float twinkle = 0.55 + 0.45 * sin(phase * (2.0 + floor(h2 * 3.0)) + h.x * TAU * 3.0);
            float sz = mix(0.0045, 0.012, h2 * h2);
            float core = exp(-dist * dist / (sz * sz));

            // 4-point diffraction star flare on brightest sparks
            float flare = 0.0;
            if (h2 > 0.72) {
                flare = exp(-abs(du) * 140.0 - abs(dv) * 28.0) +
                        exp(-abs(dv) * 140.0 - abs(du) * 28.0);
                flare *= 0.42;
            }

            vec3 sparkCol = mix(COL_GOLD, COL_WHITE_GOLD, smoothstep(0.4, 0.95, h2));
            acc += sparkCol * (core * 1.4 + flare) * twinkle;
        }
    }

    return acc * mix(0.65, 1.25, openAmt);
}

// ----------------------------------------------------------------------------
// Orbiting Arcane Runes around the Outer Rim
// ----------------------------------------------------------------------------
vec3 evalRimRunes(vec2 lp, vec2 ab, float dEll, float phase, float openAmt) {
    if (dEll < 0.04 || dEll > 0.40) return vec3(0.0);

    vec2 q = lp / max(ab, vec2(1e-4));
    float ang = atan(q.y, q.x);

    const float N = 12.0;
    float u = (ang + PI) / TAU * N;
    float baseIdx = floor(u + 0.5);

    vec3 col = vec3(0.0);
    for (int k = -1; k <= 1; k++) {
        float idx = mod(baseIdx + float(k) + N, N);
        float a0 = (idx / N) * TAU - PI;

        // Subtle floating orbital oscillation (seamless 3s loop)
        float bobA = 0.035 * sin(phase + idx * 1.618);
        float bobR = 0.020 * cos(phase * 2.0 + idx * 2.399);
        float a = a0 + bobA;

        // Place rune at uniform offset outside ellipse perimeter
        vec2 onEll = vec2(cos(a), sin(a)) * ab;
        vec2 outNormal = normalize(vec2(cos(a) / max(ab.x, 1e-4), sin(a) / max(ab.y, 1e-4)));
        vec2 runePos = onEll + outNormal * (0.195 + bobR);

        // Local upright-ish slightly tilted rune frame
        vec2 rp = (lp - runePos) / 0.115;
        if (dot(rp, rp) > 1.8) continue;
        rp = rot2(0.18 * sin(phase + idx)) * rp;

        int gid = int(mod(idx, 4.0));
        float d = sdRune(rp, gid);

        float stroke = exp(-max(d - 0.022, 0.0) * 52.0);
        float halo   = exp(-max(d, 0.0) * 10.5) * 0.38;
        float pulse  = 0.72 + 0.28 * sin(phase * 2.0 - idx * 0.85);

        // Fade bottommost rune softly where it nears the floor
        vec3 pCenter = getPortalCenter(ab);
        float floorFade = smoothstep(-pCenter.y + 0.05, -pCenter.y + 0.30, runePos.y);
        vec3 rCol = mix(COL_GOLD, COL_WHITE_GOLD, stroke * 0.72);
        col += rCol * (stroke * 1.15 + halo) * pulse * floorFade;
    }

    return col * mix(0.6, 1.15, openAmt);
}

// ----------------------------------------------------------------------------
// Deep Swirling Vortex Interior (3-layer parallax for 3D tunnel depth)
// ----------------------------------------------------------------------------
vec3 evalVortexLayer(vec2 lp, vec2 ab, float phase, float depthIdx) {
    vec2 q = lp / max(ab, vec2(1e-4));
    float r = length(q);
    if (r >= 1.04) return vec3(0.0);

    float ang = atan(q.y, q.x);
    float rSafe = max(r, 0.035);

    // Logarithmic spiral coordinates (100% seamless in 3s via integer multiples of phase)
    float twist = 5.4 + depthIdx * 1.1;
    float s1 = ang + twist * log(rSafe) - phase * 2.0 + depthIdx * 1.4;
    float s2 = ang + (twist * 0.68) * log(rSafe) - phase * 1.0 - depthIdx * 0.9;

    // Periodic domain warp using cos/sin -> ZERO branch cut seam!
    vec2 wCoord1 = vec2(cos(s1), sin(s1)) * (1.85 + r * 1.4);
    vec2 wCoord2 = vec2(cos(s2), sin(s2)) * (2.60 + r * 1.8);
    float n1 = fbm4(wCoord1 + vec2(r * 2.8, depthIdx * 3.1));
    float n2 = fbm4(wCoord2 - vec2(r * 2.2, depthIdx * 1.7));

    // Crisp luminous swirling filament ribbons
    float rib1 = pow(clamp(0.5 + 0.5 * sin(s1 * 3.0 + n1 * 4.2), 0.0, 1.0), 4.5);
    float rib2 = pow(clamp(0.5 + 0.5 * sin(s2 * 5.0 + n2 * 3.4), 0.0, 1.0), 6.0);
    float fineStrand = pow(clamp(0.5 + 0.5 * sin(s1 * 9.0 + n1 * 5.5), 0.0, 1.0), 9.0);

    // Radial vortex ring envelope: bright swirling arms around a dark starry void core
    float outerFade = smoothstep(1.00, 0.84, r);
    float coreVoid  = smoothstep(0.24, 0.58, r);
    float ringFocus = outerFade * coreVoid;

    // Color layering: cobalt outer aura -> turquoise-cyan bright filaments -> white-cyan crests
    vec3 col = vec3(0.0);
    col += COL_COBALT * (0.45 * n1 + 0.55 * rib1) * outerFade * smoothstep(0.18, 0.72, r);
    col += COL_CYAN   * (rib1 * 0.95 + rib2 * 0.85) * ringFocus;
    col += vec3(0.75, 0.98, 1.0) * fineStrand * ringFocus * 0.85;

    // Deep starry void core at the center of the portal
    if (depthIdx < 0.5) {
        float starRot = phase * 0.0; // subtle rotation via periodic grid
        vec2 starUV = rot2(0.35 * sin(phase)) * q * 16.0;
        vec2 sid = floor(starUV);
        vec2 sf = fract(starUV) - 0.5;
        vec2 sh = hash22(sid + vec2(19.3, 47.1));
        float sDist = length(sf - (sh - 0.5) * 0.65);
        float star = smoothstep(0.11, 0.01, sDist) * step(0.84, sh.x);
        float tw = 0.5 + 0.5 * sin(phase * 2.0 + sh.y * TAU * 4.0);
        float coreMask = smoothstep(0.62, 0.16, r);
        col += mix(COL_CYAN, COL_WHITE_GOLD, sh.y) * star * tw * coreMask * 0.9;
    }

    return col;
}

// ----------------------------------------------------------------------------
// Complete Portal Plane & Parallax Volumetric Evaluation
// ----------------------------------------------------------------------------
vec4 evalPortal(vec3 ro, vec3 rd, float maxT, float openAmt, float phase, bool isReflection) {
    // Intersect ray with portal plane z = 0
    if (abs(rd.z) < 1e-5) return vec4(0.0);
    float t0 = -ro.z / rd.z;
    if (t0 <= 0.02 || t0 >= maxT) return vec4(0.0);

    vec3 hit0 = ro + rd * t0;
    vec2 ab = getPortalAxes(openAmt);
    vec3 pCenter = getPortalCenter(ab);
    vec2 lp = hit0.xy - pCenter.xy;

    // Generous bounding reject (warmHalo decays to <0.001 well inside)
    if (abs(lp.x) > ab.x + 1.8 || abs(lp.y) > ab.y + 1.8) return vec4(0.0);

    float dEll = sdEllipseApprox(lp, ab);
    vec2 q = lp / max(ab, vec2(1e-4));
    float eR = length(q);
    float ang = atan(q.y, q.x);

    // Inside portal void opacity (blocks background behind the rift)
    float insideMask = smoothstep(0.015, -0.025, dEll);

    // Dark dimensional void base inside the portal
    vec3 voidBase = mix(vec3(0.010, 0.016, 0.045), COL_OBSIDIAN * 0.75, smoothstep(0.25, 0.95, eR));

    // 3-layer parallax swirling vortex inside the rift
    vec3 vortex = vec3(0.0);
    if (eR < 1.05) {
        float depthOffsets[3];
        depthOffsets[0] = 0.00;
        depthOffsets[1] = -0.10;
        depthOffsets[2] = -0.22;
        float weights[3];
        weights[0] = 0.62;
        weights[1] = 0.42;
        weights[2] = 0.28;

        for (int i = 0; i < 3; i++) {
            float ti = (depthOffsets[i] - ro.z) / rd.z;
            if (ti > 0.01) {
                vec2 lpi = (ro + rd * ti).xy - pCenter.xy;
                vortex += evalVortexLayer(lpi, ab * (1.0 - float(i) * 0.04), phase, float(i)) * weights[i];
            }
        }
    }

    // ---- Blazing Incandescent White-Gold Event-Horizon Ring ----
    // Subtle azimuthal energy shimmer (seamless 3s loop)
    float rimPulse = 0.88 + 0.12 * sin(ang * 4.0 - phase * 2.0) * cos(ang * 7.0 + phase);
    float rimBright = mix(0.70, 1.32, openAmt) * rimPulse;

    // Multi-layered concentric golden filaments (signature detail from 10.png)
    float coreBand   = exp(-pow(dEll / 0.024, 2.0));
    float innerWire1 = exp(-pow((dEll + 0.036) / 0.0075, 2.0));
    float innerWire2 = exp(-pow((dEll + 0.068) / 0.0055, 2.0));
    float outerWire  = exp(-pow((dEll - 0.038) / 0.0070, 2.0));
    float warmHalo   = exp(-abs(dEll) * 9.5) * 0.72 + exp(-abs(dEll) * 3.4) * 0.20;
    // Soft cyan-gold energy bridge right inside the golden ring
    float innerCyan  = exp(-pow((dEll + 0.085) / 0.048, 2.0)) * insideMask;

    vec3 rimCol = vec3(0.0);
    rimCol += COL_WHITE_GOLD * (coreBand * 1.85 + innerWire1 * 1.15 + outerWire * 0.85) * rimBright;
    rimCol += COL_GOLD       * (warmHalo * 1.15 + innerWire2 * 0.85) * rimBright;
    rimCol += COL_CYAN       * innerCyan * 0.55 * mix(0.6, 1.1, openAmt);

    // Orbiting runes & sparkling stardust around the rim
    vec3 runes  = evalRimRunes(lp, ab, dEll, phase, openAmt);
    vec3 sparks = isReflection
        ? evalRimSparks(lp, ab, dEll, phase, openAmt) * 0.65
        : evalRimSparks(lp, ab, dEll, phase, openAmt);

    // Combine inside void + vortex + additive blazing ring, runes & sparks
    vec3 col = (voidBase + vortex * mix(0.65, 1.20, openAmt)) * insideMask;
    col += rimCol + runes + sparks;

    // Floor clip: portal hovers just above y = 0 (cleanly fades below y = 0.02)
    float aboveFloor = smoothstep(-0.02, 0.04, hit0.y);
    col *= aboveFloor;
    float alpha = insideMask * aboveFloor;

    return vec4(col, alpha);
}

// ----------------------------------------------------------------------------
// Cascading Golden Stardust Trail & Floor Runes on the Wet Obsidian Arena
// ----------------------------------------------------------------------------
vec3 evalFloorStardust(vec2 xz, float phase, float openAmt) {
    // Graceful curving stream spilling from lower-right portal rim onto the floor
    vec3 acc = vec3(0.0);

    // Curved ribbon spine in xz plane: starts near (0.32, 0.08), arcs to (0.92, 0.55) then curls back
    vec2 p = xz - vec2(0.45, 0.32);
    float r = length(p);
    if (r < 1.15) {
        // Multi-scale sparkling dust cells along the floor trail
        for (int layer = 0; layer < 2; layer++) {
            float fl = float(layer);
            float scale = 12.0 + fl * 9.0;
            vec2 g = xz * scale;
            vec2 id = floor(g);
            vec2 f = fract(g) - 0.5;
            vec2 h = hash22(id + fl * 37.0);
            float h2 = hash21(id * 2.3 + fl * 13.0);

            // Spiral trail mask
            vec2 wp = (id + h) / scale;
            float arcAng = atan(wp.y - 0.34, wp.x - 0.42);
            float arcR = length(wp - vec2(0.42, 0.34));
            float trailMask = exp(-pow((arcR - 0.36 - 0.08 * sin(arcAng * 2.0)) / 0.18, 2.0));
            trailMask *= smoothstep(-0.15, 0.35, wp.x) * smoothstep(-0.25, 0.10, wp.y);
            // Also scatter subtle sparks right under the portal base
            float basePool = exp(-dot(wp - vec2(0.0, 0.25), wp - vec2(0.0, 0.25)) * 2.4) * 0.55;
            float density = clamp(trailMask + basePool, 0.0, 1.0);

            if (density > 0.08 && h2 > 0.35) {
                vec2 jitter = (h - 0.5) * 0.72;
                float dist = length(f - jitter);
                float tw = 0.5 + 0.5 * sin(phase * 2.0 + h.x * TAU * 3.0);
                float sz = mix(0.06, 0.16, h2 * h2);
                float spark = exp(-dist * dist / (sz * sz));
                vec3 sCol = mix(COL_GOLD, COL_WHITE_GOLD, smoothstep(0.5, 0.95, h2));
                acc += sCol * spark * tw * density * 1.45;
            }
        }
    }

    // Two crisp glowing arcane runes hovering/reflected on the wet floor (matching 10.png!)
    // Rune A: bottom-center-foreground
    {
        vec2 rp = (xz - vec2(-0.08, 0.82)) / 0.19;
        rp = rot2(0.28) * rp;
        if (dot(rp, rp) < 1.6) {
            float d = sdRune(rp, 0);
            float s = exp(-max(d - 0.025, 0.0) * 38.0);
            float h = exp(-max(d, 0.0) * 8.0) * 0.35;
            acc += mix(COL_GOLD, COL_WHITE_GOLD, s * 0.7) * (s * 1.25 + h) * (0.8 + 0.2 * sin(phase * 2.0));
        }
    }
    // Rune B: lower-right near stardust trail
    {
        vec2 rp = (xz - vec2(0.46, 0.52)) / 0.16;
        rp = rot2(-0.42) * rp;
        if (dot(rp, rp) < 1.6) {
            float d = sdRune(rp, 2);
            float s = exp(-max(d - 0.025, 0.0) * 38.0);
            float h = exp(-max(d, 0.0) * 8.0) * 0.35;
            acc += mix(COL_GOLD, COL_WHITE_GOLD, s * 0.7) * (s * 1.15 + h) * (0.8 + 0.2 * cos(phase * 2.0));
        }
    }

    return acc * mix(0.6, 1.15, openAmt);
}

// ----------------------------------------------------------------------------
// Environment / Studio Backdrop (rich atmospheric obsidian arena, never pure black)
// ----------------------------------------------------------------------------
vec3 evalEnvironment(vec3 rd, int lightMode, float openAmt) {
    float elev = clamp(rd.y * 0.5 + 0.5, 0.0, 1.0);
    vec3 bg = mix(COL_OBSIDIAN * 0.95, vec3(0.055, 0.095, 0.19), smoothstep(0.42, 0.95, elev));

    // Soft cool studio overhead/side key reflection panels for wet tile readability
    vec3 panelDir1 = normalize(vec3(-0.65, 0.42, -0.62));
    vec3 panelDir2 = normalize(vec3( 0.70, 0.34, -0.58));
    float p1 = pow(max(dot(rd, panelDir1), 0.0), 8.0);
    float p2 = pow(max(dot(rd, panelDir2), 0.0), 10.0);
    bg += vec3(0.14, 0.22, 0.38) * p1 * 0.85;
    bg += vec3(0.10, 0.18, 0.34) * p2 * 0.65;

    if (lightMode == 2) {
        // Grazing raking warm/cool rim
        vec3 grazeDir = normalize(vec3(0.92, 0.16, 0.35));
        bg += vec3(0.28, 0.26, 0.24) * pow(max(dot(rd, grazeDir), 0.0), 12.0);
    } else if (lightMode == 3) {
        // Strong cool-cyan backlight behind portal
        vec3 backDir = normalize(vec3(0.08, 0.28, -0.95));
        bg += mix(COL_COBALT, COL_CYAN, 0.55) * pow(max(dot(rd, backDir), 0.0), 7.0) * 1.15;
    }

    // Subtle atmospheric portal aura glow in the background
    vec3 toPortal = normalize(PORTAL_CENTER - vec3(0.0, 1.4, 3.2));
    float aura = pow(max(dot(rd, toPortal), 0.0), 6.0);
    bg += mix(COL_COBALT, COL_GOLD, 0.22) * aura * 0.10 * mix(0.5, 1.0, openAmt);

    return bg;
}

// ----------------------------------------------------------------------------
// ACES Filmic Tone Mapping (Narkowicz fit, NaN-safe, smooth highlight roll-off)
// ----------------------------------------------------------------------------
vec3 acesToneMap(vec3 x) {
    x = max(x, vec3(0.0));
    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;
    return clamp((x * (a * x + b)) / max(x * (c * x + d) + e, vec3(1e-5)), 0.0, 1.0);
}

// ----------------------------------------------------------------------------
// Clay / Neutral Grayscale Study Renderer (uLightMode == 1)
// ----------------------------------------------------------------------------
vec3 renderClayMode(vec3 ro, vec3 rd, float openAmt, float phase) {
    vec2 ab = getPortalAxes(openAmt);
    float t = 0.0;
    int hitMat = -1;
    for (int i = 0; i < 96; i++) {
        vec3 p = ro + rd * t;
        int m;
        float d = mapClay(p, ab, m);
        if (d < 0.0018) {
            hitMat = m;
            break;
        }
        t += d * 0.85;
        if (t > 24.0) break;
    }

    vec3 bg = vec3(mix(0.10, 0.20, clamp(rd.y * 0.5 + 0.5, 0.0, 1.0)));
    if (hitMat < 0) return bg;

    vec3 p = ro + rd * t;
    vec3 N = calcClayNormal(p, ab);
    vec3 V = -rd;

    vec3 L1 = normalize(vec3(-0.55, 0.72, 0.42));
    vec3 L2 = normalize(vec3( 0.65, 0.45, -0.55));
    float diff1 = max(dot(N, L1), 0.0);
    float diff2 = max(dot(N, L2), 0.0);
    vec3 H1 = normalize(L1 + V);
    float spec1 = pow(max(dot(N, H1), 0.0), 36.0);
    float fres = pow(1.0 - max(dot(N, V), 0.0), 4.0);

    float albedo = 0.42;
    if (hitMat == 0) {
        FloorInfo fi = sampleFloor(p.xz);
        albedo = mix(0.36 + 0.08 * fi.tileId, 0.16, fi.grout);
    } else if (hitMat == 1) {
        albedo = 0.68;
    } else {
        albedo = 0.28;
    }

    float lum = albedo * (0.24 + 0.72 * diff1 + 0.28 * diff2) + spec1 * 0.24 + fres * 0.14;
    // Distance fog into neutral studio grey
    float fog = 1.0 - exp(-t * t * 0.008);
    lum = mix(lum, bg.x, fog);
    return vec3(lum);
}

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

    float openAmt = clamp(uOpen, 0.0, 1.0);
    // Seamless 3.0-second loop phase
    float phase = fract(uTime / 3.0) * TAU;

    // Camera setup: 0 = Hero 3/4 view, 1 = ~2.5x macro close-up on rim, sparks & reflection
    vec3 ro, ta;
    float focal;
    if (uCamMode == 1) {
        ro = vec3(-0.68, 0.78, 1.56);
        ta = vec3( 0.16, 0.56, 0.04);
        focal = 2.35;
    } else {
        ro = vec3(-1.18, 1.72, 4.18);
        ta = vec3( 0.00, 1.12, 0.00);
        focal = 1.58;
    }

    vec3 cw = normalize(ta - ro);
    vec3 cu = normalize(cross(cw, vec3(0.0, 1.0, 0.0)));
    vec3 cv = cross(cu, cw);
    vec3 rd = normalize(uv.x * cu + uv.y * cv + focal * cw);

    // uLightMode == 1: Pure neutral grayscale clay study with emission muted
    if (uLightMode == 1) {
        vec3 clay = renderClayMode(ro, rd, openAmt, phase);
        clay = acesToneMap(clay);
        clay = pow(max(clay, vec3(0.0)), vec3(1.0 / 2.2));
        fragColor = vec4(clay, 1.0);
        return;
    }

    // ------------------------------------------------------------------------
    // Trace Wet Tiled Obsidian Floor (y = 0 plane + heightfield refinement)
    // ------------------------------------------------------------------------
    vec3 col = evalEnvironment(rd, uLightMode, openAmt);
    float floorT = 1e5;

    if (rd.y < -1e-4) {
        float tPlane = -ro.y / rd.y;
        if (tPlane > 0.05 && tPlane < 32.0) {
            // 2-step heightfield refinement for accurate tile bevel parallax
            float tHit = tPlane;
            for (int i = 0; i < 3; i++) {
                vec3 hp = ro + rd * tHit;
                float h = sampleFloor(hp.xz).height;
                tHit -= (hp.y - h) / min(rd.y, -0.05);
            }
            floorT = max(tHit, 0.05);
            vec3 p = ro + rd * floorT;
            FloorInfo fi = sampleFloor(p.xz);
            vec3 N = calcFloorNormal(p);
            vec3 V = -rd;
            float NdotV = max(dot(N, V), 0.0);

            // Wet obsidian base color (rich dark slate-indigo, darker in grout)
            vec3 baseAlbedo = COL_OBSIDIAN * (0.85 + 0.45 * fi.tileId);
            baseAlbedo = mix(baseAlbedo, COL_OBSIDIAN * 0.42, fi.grout);

            // Schlick Fresnel modulated by puddle wetness
            float F0 = mix(0.045, 0.24, fi.wet);
            float fres = F0 + (1.0 - F0) * pow(1.0 - NdotV, 4.2);

            // Environment reflection on wet stone tiles
            vec3 R = reflect(rd, N);
            vec3 envRefl = evalEnvironment(R, uLightMode, openAmt);

            // ---- Luminous Golden-Cyan Mirror Reflection of the Portal ----
            // Perturbed planar mirror reflection across the wet obsidian tiles
            vec4 portalRefl = evalPortal(p + vec3(0.0, 0.002, 0.0), R, 22.0, openAmt, phase, true);
            // Soft blurred reflection for damp non-puddle stone tiles
            vec3 Rsoft = normalize(mix(reflect(rd, vec3(0.0, 1.0, 0.0)), R, 0.45));
            vec4 portalReflSoft = evalPortal(p + vec3(0.0, 0.002, 0.0), Rsoft, 22.0, openAmt, phase, true);
            vec3 reflPortalCol = mix(portalReflSoft.rgb * 0.58, portalRefl.rgb * 0.92, fi.wet);
            // Dampen reflection inside dry recessed grout seams
            reflPortalCol *= (1.0 - 0.72 * fi.grout);

            // ---- Direct Analytical Lighting from Portal & Arena Keys ----
            // 1) Lower golden event-horizon rim pool light
            vec3 LgoldPos = vec3(0.0, 0.24, 0.0);
            vec3 toGold = LgoldPos - p;
            float dGold = length(toGold);
            vec3 Lg = toGold / max(dGold, 1e-4);
            float attGold = 1.0 / (0.28 + 1.15 * dGold * dGold);
            float diffGold = max(dot(N, Lg), 0.0);
            vec3 Hg = normalize(Lg + V);
            float specExp = mix(24.0, 160.0, fi.wet);
            float specGold = pow(max(dot(N, Hg), 0.0), specExp) * mix(0.35, 1.25, fi.wet);

            // 2) Swirling cyan vortex fill light
            vec3 LcyanPos = PORTAL_CENTER;
            vec3 toCyan = LcyanPos - p;
            float dCyan = length(toCyan);
            vec3 Lc = toCyan / max(dCyan, 1e-4);
            float attCyan = 1.0 / (0.65 + 0.55 * dCyan * dCyan);
            float diffCyan = max(dot(N, Lc), 0.0);
            vec3 Hc = normalize(Lc + V);
            float specCyan = pow(max(dot(N, Hc), 0.0), specExp * 0.65) * mix(0.25, 0.90, fi.wet);

            // 3) Mode-dependent studio key / grazing / backlight
            vec3 Lkey = normalize(vec3(-0.60, 0.55, -0.58));
            vec3 LkeyCol = vec3(0.22, 0.34, 0.56);
            if (uLightMode == 2) {
                Lkey = normalize(vec3(0.92, 0.16, 0.35));
                LkeyCol = vec3(0.55, 0.50, 0.44);
            } else if (uLightMode == 3) {
                Lkey = normalize(vec3(0.08, 0.24, -0.96));
                LkeyCol = mix(COL_COBALT, COL_CYAN, 0.5) * 0.85;
            }
            float diffKey = max(dot(N, Lkey), 0.0);
            vec3 Hk = normalize(Lkey + V);
            float specKey = pow(max(dot(N, Hk), 0.0), mix(18.0, 110.0, fi.wet)) * mix(0.22, 0.85, fi.wet);

            float openLum = mix(0.60, 1.25, openAmt);
            vec3 floorCol = baseAlbedo * (0.38 + diffKey * LkeyCol * 1.4);
            floorCol += baseAlbedo * COL_GOLD * diffGold * attGold * 3.2 * openLum;
            floorCol += baseAlbedo * COL_CYAN * diffCyan * attCyan * 2.1 * openLum;

            // Specular & mirror reflections
            floorCol += LkeyCol * specKey * (1.0 - 0.5 * fi.grout);
            floorCol += COL_GOLD * specGold * attGold * 1.15 * openLum;
            floorCol += COL_CYAN * specCyan * attCyan * 0.85 * openLum;
            floorCol += envRefl * fres * mix(0.55, 1.15, fi.wet);
            floorCol += reflPortalCol * mix(0.32, 0.92, fres + fi.wet * 0.35);

            // Cascading golden stardust & glowing runes on the wet floor
            floorCol += evalFloorStardust(p.xz, phase, openAmt);

            // Atmospheric depth fade into dark obsidian horizon
            float fog = 1.0 - exp(-floorT * floorT * 0.0085);
            col = mix(floorCol, evalEnvironment(rd, uLightMode, openAmt), fog);
        }
    }

    // ------------------------------------------------------------------------
    // Composite Standing Arcane Portal in Front of Floor/Backdrop
    // ------------------------------------------------------------------------
    vec4 portal = evalPortal(ro, rd, floorT, openAmt, phase, false);
    // Inside the elliptical rift replaces background with deep starry void + vortex,
    // while outer glowing rim, runes, and sparks blend additively over the arena!
    col = col * (1.0 - portal.a) + portal.rgb;

    // Subtle volumetric golden-cyan bloom glow around the portal in screen/ray space
    vec2 ab = getPortalAxes(openAmt);
    vec3 pCenter = getPortalCenter(ab);
    vec3 toC = pCenter - ro;
    float proj = dot(toC, rd);
    if (proj > 0.0 && proj < floorT + 1.5) {
        vec3 closest = ro + rd * proj;
        vec2 dp = (closest.xy - pCenter.xy) / max(ab, vec2(1e-4));
        float rDist = length(dp);
        float glow = exp(-abs(rDist - 1.0) * 3.8) * exp(-abs(closest.z) * 1.8);
        col += mix(COL_GOLD, COL_CYAN, 0.25) * glow * 0.12 * mix(0.55, 1.1, openAmt);
    }

    // Gentle vignette that keeps corners richly lit (never crushed to pure black)
    float vig = 1.0 - 0.18 * dot(uv, uv);
    col *= vig;

    // Gentle exposure & ACES filmic tone mapping (0% NaN, <1% clipped, <2% black)
    col *= 0.88;
    // Subtle ambient obsidian floor lift to ensure zero crushed black pixels without washing out shadows
    col = max(col, COL_OBSIDIAN * 0.12);
    col = acesToneMap(col);
    col = pow(max(col, vec3(0.0)), vec3(1.0 / 2.2));

    fragColor = vec4(col, 1.0);
}
