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

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

vec3 hash32(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
    p3 += dot(p3, p3.yxz + 33.33);
    return fract((p3.xxy + p3.yzz) * p3.zyx);
}

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

float fbm2(vec2 p) {
    float v = 0.0;
    float a = 0.5;
    mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
    for (int i = 0; i < 4; i++) {
        v += a * valueNoise(p);
        p = rot * p * 2.03 + 11.7;
        a *= 0.5;
    }
    return v;
}

// -----------------------------------------------------------------------------
// L-Bracket Sheet-Metal Geometry Constants & Transforms
// -----------------------------------------------------------------------------
const float SHEET_HT   = 0.028;  // half-thickness (5.6 cm scale model)
const float EDGE_BEVEL = 0.0065; // crisp rolled/sheared edge radius
const float BEND_RC    = 0.165;  // centerline bend radius
const float X_BEND     = -0.18;  // horizontal bend tangent x
const float X_MAX      = 0.64;   // base flange tip x
const float Y_MAX      = 1.06;   // upright flange top y
const float HALF_W     = 0.68;   // half-width along local z

const float C_Y = SHEET_HT + BEND_RC; // bend center y
const float X_VERT = X_BEND - BEND_RC; // vertical centerline x
const float LEN_V = Y_MAX - C_Y;
const float LEN_ARC = 0.5 * PI * BEND_RC;
const float LEN_H = X_MAX - X_BEND;

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

// World -> Bracket local space (rotated ~28 deg for dramatic 3/4 presentation)
vec3 toBracketLocal(vec3 p) {
    vec3 q = p;
    q.xz = rot2(-0.46) * q.xz;
    return q;
}

vec3 dirToBracketLocal(vec3 d) {
    vec3 q = d;
    q.xz = rot2(-0.46) * q.xz;
    return q;
}

vec3 dirFromBracketLocal(vec3 d) {
    vec3 q = d;
    q.xz = rot2(0.46) * q.xz;
    return q;
}

float sdSegment2D(vec2 p, vec2 a, vec2 b) {
    vec2 pa = p - a, ba = b - a;
    float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
    return length(pa - ba * h);
}

float smin(float a, float b, float k) {
    float h = max(k - abs(a - b), 0.0) / k;
    return min(a, b) - h * h * k * 0.25;
}

float smax(float a, float b, float k) {
    return -smin(-a, -b, k);
}

// Exact signed distance to the bent L-bracket in world space
float mapHero(vec3 pWorld) {
    vec3 p = toBracketLocal(pWorld);

    // 1. Centerline distance in (x, y) cross-section
    vec2 q = p.xy;
    float dHoriz = sdSegment2D(q, vec2(X_BEND, SHEET_HT), vec2(X_MAX, SHEET_HT));
    float dVert  = sdSegment2D(q, vec2(X_VERT, C_Y), vec2(X_VERT, Y_MAX));

    vec2 vc = q - vec2(X_BEND, C_Y);
    float dCenter = min(dHoriz, dVert);
    if (vc.x < 0.0 && vc.y < 0.0) {
        float dArc = abs(length(vc) - BEND_RC);
        dCenter = min(dCenter, dArc);
    }

    // 2. Extrude along width z and round sheared sheet edges
    float dCross = dCenter - (SHEET_HT - EDGE_BEVEL);
    float dWidth = abs(p.z) - (HALF_W - EDGE_BEVEL);
    float dPlate = length(max(vec2(dCross, dWidth), 0.0)) + min(max(dCross, dWidth), 0.0) - EDGE_BEVEL;

    // 3. Punched industrial mounting holes (2 on horizontal base, 2 on vertical upright)
    // Base flange holes: centered at x = 0.32, z = +/- 0.34
    vec2 hBase = vec2(p.x - 0.32, abs(p.z) - 0.34);
    float dHoleBase = length(hBase) - 0.082;
    // Bounded cylinder inside base flange slab (negative inside hole, positive outside)
    float holeCylBase = max(dHoleBase, abs(p.y - SHEET_HT) - 0.12);

    // Upright flange holes: centered at y = 0.74, z = +/- 0.34
    vec2 hVert = vec2(p.y - 0.74, abs(p.z) - 0.34);
    float dHoleVert = length(hVert) - 0.082;
    // Bounded cylinder inside upright flange slab (negative inside hole, positive outside)
    float holeCylVert = max(dHoleVert, abs(p.x - X_VERT) - 0.12);

    // Subtract bounded hole cylinders with subtle beveled punch edge
    float dBracket = smax(dPlate, -holeCylBase, 0.006);
    dBracket = smax(dBracket, -holeCylVert, 0.006);

    return dBracket;
}

float mapScene(vec3 p) {
    return min(mapHero(p), p.y);
}

// Unit-weight tetrahedral normal (Rule 1)
vec3 calcNormalHero(vec3 p) {
    const float e = 0.0005;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * mapHero(p + k.xyy * e) +
        k.yyx * mapHero(p + k.yyx * e) +
        k.yxy * mapHero(p + k.yxy * e) +
        k.xxx * mapHero(p + k.xxx * e)
    );
}

// Hero-only soft shadow (Rule 3: clean res = min(res, k*h/t), no ph!)
float softShadowHero(vec3 ro, vec3 rd, float tMax, float k) {
    float res = 1.0;
    float t = 0.025;
    for (int i = 0; i < 64; i++) {
        float h = mapHero(ro + rd * t);
        res = min(res, k * h / t);
        if (res < 0.002 || t > tMax) break;
        t += max(h, 0.015);
    }
    return clamp(res, 0.0, 1.0);
}

// Ambient occlusion against hero + bench
float calcAO(vec3 pos, vec3 nor) {
    float occ = 0.0;
    float sca = 1.0;
    for (int i = 0; i < 5; i++) {
        float h = 0.018 + 0.065 * float(i);
        float d = mapScene(pos + h * nor);
        occ += (h - d) * sca;
        sca *= 0.72;
    }
    return clamp(1.0 - 2.2 * occ, 0.08, 1.0);
}

// -----------------------------------------------------------------------------
// Continuous Sheet-Metal Surface Parameterization (wraps seamlessly over bend)
// -----------------------------------------------------------------------------
struct SheetFrame {
    vec2 uv;        // continuous sheet-surface coordinates (arcLength, z)
    vec3 T;         // world-space tangent along arcLength
    vec3 B;         // world-space bitangent along sheet width z
    float edgeMask; // 1.0 on cut/sheared rims & hole walls, 0.0 on flat/bent faces
    float sideId;   // +1 outer face, -1 inner face (distinct zinc crystal layers)
};

SheetFrame getSheetFrame(vec3 pWorld, vec3 nWorld) {
    vec3 p = toBracketLocal(pWorld);
    vec3 n = normalize(dirToBracketLocal(nWorld));
    vec2 q = p.xy;

    float dHoriz = sdSegment2D(q, vec2(X_BEND, SHEET_HT), vec2(X_MAX, SHEET_HT));
    float dVert  = sdSegment2D(q, vec2(X_VERT, C_Y), vec2(X_VERT, Y_MAX));
    vec2 vc = q - vec2(X_BEND, C_Y);
    float dArc = 1e5;
    if (vc.x < 0.0 && vc.y < 0.0) {
        dArc = abs(length(vc) - BEND_RC);
    }

    float s = 0.0;
    vec3 T_loc = vec3(1.0, 0.0, 0.0);
    vec3 N_ideal = vec3(0.0, 1.0, 0.0);
    float side = 1.0;

    if (dArc <= dHoriz && dArc <= dVert) {
        // On the 90-degree cylindrical bend
        float ang = atan(vc.y, vc.x); // in [-PI, -PI/2]
        float frac = clamp((ang + PI) / (0.5 * PI), 0.0, 1.0);
        s = LEN_V + frac * LEN_ARC;
        vec2 rad = normalize(vc);
        // Tangent follows increasing angle (from vertical down to horizontal right)
        T_loc = vec3(-rad.y, rad.x, 0.0);
        side = (length(vc) > BEND_RC) ? 1.0 : -1.0;
        N_ideal = vec3(rad * side, 0.0);
    } else if (dVert <= dHoriz) {
        // On the vertical upright flange
        s = Y_MAX - clamp(q.y, C_Y, Y_MAX);
        T_loc = vec3(0.0, -1.0, 0.0);
        side = (q.x < X_VERT) ? 1.0 : -1.0;
        N_ideal = vec3(-side, 0.0, 0.0);
    } else {
        // On the horizontal base flange
        s = LEN_V + LEN_ARC + clamp(q.x - X_BEND, 0.0, LEN_H);
        T_loc = vec3(1.0, 0.0, 0.0);
        side = (q.y < SHEET_HT) ? 1.0 : -1.0;
        N_ideal = vec3(0.0, -side, 0.0);
    }

    vec3 B_loc = vec3(0.0, 0.0, 1.0);
    // Ensure right-handed frame relative to actual surface normal
    if (dot(cross(T_loc, B_loc), n) < 0.0) {
        B_loc = -B_loc;
    }

    // Detect sheared outer edges and punched hole walls by comparing normal to ideal face normal
    float faceAlign = abs(dot(n, N_ideal));
    float edgeMask = 1.0 - smoothstep(0.55, 0.88, faceAlign);

    SheetFrame sf;
    sf.uv = vec2(s, p.z);
    sf.T = normalize(dirFromBracketLocal(T_loc));
    sf.B = normalize(dirFromBracketLocal(B_loc));
    sf.edgeMask = edgeMask;
    sf.sideId = side;
    return sf;
}

// -----------------------------------------------------------------------------
// Hot-Dip Galvanized Zinc Spangle (Sharp Voronoi + 6-Fold HCP Dendrites)
// -----------------------------------------------------------------------------
struct SpangleData {
    vec2  grainId;
    float edgeDist;     // distance to sharp polygonal crystal boundary
    float dendrite;     // feathery 6-fold HCP crystal height [0..1]
    vec2  microSlope;   // local crystal micro-relief gradient
    vec2  facetTilt;    // discrete grain crystallographic normal tilt
    float grainBright;  // discrete reflectance tier (mirror-bright vs satin-dark)
    float grainRough;   // discrete per-grain roughness
    vec3  grainTint;    // subtle cool-zinc / silver-pewter crystal tint
};

SpangleData evalZincSpangle(vec2 uv, float sideId, float openParam) {
    // uOpen (0..1): 0 = fine micro-spangle, 1 = bold large architectural spangle
    float scale = 17.5 * pow(3.6 / 17.5, clamp(openParam, 0.0, 1.0));

    // Offset opposite face of sheet so inner/outer faces have independent crystals
    vec2 p = uv * scale + (sideId < 0.0 ? vec2(37.4, -19.2) : vec2(0.0));

    // Tiny domain warp ONLY at microscopic scale so grain boundaries stay sharp polygons
    vec2 nCell = floor(p);
    vec2 fCell = fract(p);

    // Pass 1: Find nearest nucleation site (F1)
    float d1 = 8.0;
    vec2 bestOffset = vec2(0.0);
    vec2 bestCell = vec2(0.0);
    vec2 bestR = vec2(0.0);

    for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
            vec2 g = vec2(float(i), float(j));
            vec2 cell = nCell + g;
            // Jitter 0.86 produces authentic irregular 5-7 sided zinc polygons
            vec2 o = 0.07 + 0.86 * hash22(cell);
            vec2 r = g + o - fCell;
            float d = dot(r, r);
            if (d < d1) {
                d1 = d;
                bestOffset = o;
                bestCell = cell;
                bestR = r;
            }
        }
    }

    // Pass 2: Exact Euclidean distance to nearest polygonal Voronoi bisector
    float edgeDist = 8.0;
    for (int j = -2; j <= 2; j++) {
        for (int i = -2; i <= 2; i++) {
            vec2 g = vec2(float(i), float(j));
            vec2 cell = nCell + g;
            if (dot(cell - bestCell, cell - bestCell) < 0.5) continue;
            vec2 o = 0.07 + 0.86 * hash22(cell);
            vec2 r = g + o - fCell;
            vec2 diff = r - bestR;
            float lenD = length(diff);
            if (lenD > 1e-4) {
                float dEdge = dot(0.5 * (bestR + r), diff / lenD);
                edgeDist = min(edgeDist, dEdge);
            }
        }
    }

    // Per-grain discrete crystallographic properties
    vec3 h3 = hash32(bestCell + vec2(13.7, 5.3));
    vec3 h3b = hash32(bestCell * 1.37 + vec2(41.1, 29.8));

    // Local coordinates relative to grain's nucleation center
    vec2 lp = -bestR;
    float theta = h3.x * TAU;
    vec2 rlp = rot2(theta) * lp;

    // 6-fold hexagonal close-packed (HCP) zinc dendritic crystal growth
    float rad = length(rlp);
    float ang = atan(rlp.y, rlp.x);
    // Fold into 60-degree crystal sector
    float sector = mod(ang + PI, PI / 3.0) - PI / 6.0;
    // Coordinates aligned with primary dendrite arm in this sector
    vec2 armP = vec2(rad * cos(sector), rad * sin(sector));

    // Primary dendrite spine (sharp central rib radiating from nucleus)
    float primaryArm = exp(-abs(armP.y) * 26.0) * smoothstep(0.02, 0.14, armP.x);

    // Secondary feathery side-branches growing at 60 deg off primary arm
    float branchCoord = armP.x * 16.0 - abs(armP.y) * 9.2;
    float featherWave = 0.5 + 0.5 * cos(branchCoord * TAU + h3.y * 6.0);
    float secondary = pow(featherWave, 1.7) * exp(-abs(armP.y) * 5.5) * smoothstep(0.03, 0.18, rad);

    // Fine parallel crystalline lamellae (basal slip striations)
    float striaFreq = mix(24.0, 44.0, h3b.x);
    float stria = 0.5 + 0.5 * sin(rlp.x * striaFreq + 0.35 * sin(rlp.y * 14.0));
    // Sub-sector facet variation (each of the 6 dendritic petals can differ slightly in tilt)
    float sectorIdx = floor((ang + PI) / (PI / 3.0));
    float petalHash = hash12(bestCell * 7.13 + vec2(sectorIdx, 3.1));

    float dendrite = clamp(0.45 * primaryArm + 0.42 * secondary + 0.25 * stria, 0.0, 1.0);

    // Analytical micro-slope for crisp dendritic feather relief
    float dBranch = -sin(branchCoord * TAU + h3.y * 6.0) * exp(-abs(armP.y) * 5.5);
    float dStria  = cos(rlp.x * striaFreq) * 0.45;
    vec2 localSlope = vec2(dStria + dBranch * 0.55, -sign(armP.y) * primaryArm * 1.1 + dBranch * 0.35);
    // Rotate slope back to sheet UV frame
    vec2 microSlope = rot2(-theta) * localSlope;

    // Discrete crystallographic facet tilt per grain (up to ~14 deg) + subtle petal sub-tilt
    vec2 tiltDir = vec2(cos(h3.y * TAU), sin(h3.y * TAU));
    float tiltMag = mix(0.05, 0.24, pow(h3.z, 0.85));
    vec2 petalTilt = vec2(cos(petalHash * TAU), sin(petalHash * TAU)) * 0.035;
    vec2 facetTilt = tiltDir * tiltMag + petalTilt;

    // Abrupt metallic reflectance jump across grains:
    // ~30% mirror-bright basal grains, ~35% mid-sheen grains, ~35% satin-dark frosted grains
    float tier = h3b.y;
    float grainBright;
    float grainRough;
    if (tier > 0.68) {
        // Mirror-bright smooth basal crystal
        grainBright = mix(0.96, 1.12, (tier - 0.68) / 0.32);
        grainRough  = mix(0.11, 0.19, h3b.z);
    } else if (tier > 0.34) {
        // Medium satin-metallic spangle
        grainBright = mix(0.76, 0.92, (tier - 0.34) / 0.34);
        grainRough  = mix(0.24, 0.36, h3b.z);
    } else {
        // Dark frosted-satin prismatic crystal
        grainBright = mix(0.56, 0.72, tier / 0.34);
        grainRough  = mix(0.40, 0.56, h3b.z);
    }

    // Dendritic frost subtly modulates roughness & local sheen inside the grain
    grainRough = clamp(grainRough + (0.5 - dendrite) * 0.065, 0.09, 0.65);

    // Subtle realistic zinc alloy tint variation (cool steel-blue to silvery pewter)
    vec3 tintA = vec3(0.84, 0.87, 0.91); // crisp cool zinc silver
    vec3 tintB = vec3(0.75, 0.79, 0.84); // bluish-slate zinc
    vec3 tintC = vec3(0.87, 0.86, 0.84); // faint warm silver-pewter
    vec3 grainTint = mix(mix(tintA, tintB, h3.z), tintC, h3b.x * 0.45);

    SpangleData sd;
    sd.grainId     = bestCell;
    sd.edgeDist    = edgeDist;
    sd.dendrite    = dendrite;
    sd.microSlope  = microSlope;
    sd.facetTilt   = facetTilt;
    sd.grainBright = grainBright;
    sd.grainRough  = grainRough;
    sd.grainTint   = grainTint;
    return sd;
}

// -----------------------------------------------------------------------------
// High-Contrast Studio Environment (Softboxes + Dark Negative-Fill Flags)
// -----------------------------------------------------------------------------
vec3 evalStudioEnv(vec3 rd) {
    vec3 d = normalize(rd);

    // Subtle slow studio glint breathe with uTime (0 at uTime=0)
    float drift = 0.06 * sin(uTime * 0.35);
    vec3 dRot = d;
    dRot.xz = rot2(drift) * dRot.xz;

    // Base studio cyclorama gradient (low-key dark charcoal so softboxes pop)
    float up = clamp(d.y * 0.5 + 0.5, 0.0, 1.0);
    vec3 env = mix(vec3(0.055, 0.058, 0.064), vec3(0.14, 0.148, 0.162), smoothstep(0.35, 0.95, up));

    // Studio softbox helper (smooth rectangular light panel on unit sphere)
    // Mode 0: Hero studio (warm-neutral key softbox + cool strip rim + dark negative-fill flags)
    // Mode 1: Pure neutral grayscale studio (strictly achromatic)
    // Mode 2: Grazing raking light
    // Mode 3: Dramatic backlit rim studio

    vec3 keyCol  = vec3(1.00, 0.985, 0.96);
    vec3 fillCol = vec3(0.90, 0.95, 1.00);
    vec3 rimCol  = vec3(0.96, 0.98, 1.00);

    if (uLightMode == 1) {
        keyCol  = vec3(1.0);
        fillCol = vec3(1.0);
        rimCol  = vec3(1.0);
        env = vec3(dot(env, vec3(0.3333)));
    }

    if (uLightMode == 0 || uLightMode == 1) {
        // Overhead-left primary softbox
        vec3 kDir = normalize(vec3(-0.55, 0.72, 0.42));
        float kDot = max(dot(dRot, kDir), 0.0);
        float softbox1 = smoothstep(0.78, 0.92, kDot);
        env += keyCol * softbox1 * 4.2;

        // Tall vertical right-side strip softbox (creates crisp metallic reflection bands)
        float stripAz = abs(atan(dRot.x, dRot.z) - 1.18);
        float stripEl = abs(dRot.y - 0.32);
        float stripBox = (1.0 - smoothstep(0.12, 0.22, stripAz)) * (1.0 - smoothstep(0.28, 0.40, stripEl));
        env += fillCol * stripBox * 2.8;

        // Overhead diffuse ceiling bounce
        float ceilBox = smoothstep(0.84, 0.94, dRot.y);
        env += keyCol * ceilBox * 1.45;

        // Subtle back rim kicker
        vec3 rDir = normalize(vec3(0.25, 0.42, -0.87));
        float rimBox = smoothstep(0.84, 0.95, max(dot(dRot, rDir), 0.0));
        env += rimCol * rimBox * 2.6;

        // Dark negative-fill flags (essential for high-contrast faceted zinc spangles!)
        vec3 flag1Dir = normalize(vec3(-0.85, 0.12, -0.35));
        float flag1 = smoothstep(0.72, 0.86, max(dot(dRot, flag1Dir), 0.0));
        vec3 flag2Dir = normalize(vec3(0.35, 0.18, 0.92));
        float flag2 = smoothstep(0.76, 0.90, max(dot(dRot, flag2Dir), 0.0));
        env *= (1.0 - 0.82 * flag1);
        env *= (1.0 - 0.75 * flag2);
    } else if (uLightMode == 2) {
        // Grazing raking light: low-angle hard-edged strip from side-left
        env *= 0.65;
        vec3 gDir = normalize(vec3(-0.92, 0.24, 0.30));
        float gBox = smoothstep(0.84, 0.95, max(dot(dRot, gDir), 0.0));
        env += vec3(1.0, 0.97, 0.92) * gBox * 5.8;

        // Faint opposite cool fill so shadow side keeps detail
        vec3 fDir = normalize(vec3(0.75, 0.45, 0.48));
        float fBox = smoothstep(0.75, 0.92, max(dot(dRot, fDir), 0.0));
        env += vec3(0.82, 0.90, 1.0) * fBox * 1.1;

        // Strong overhead negative-fill flag to keep grazing contrast razor-sharp
        float topFlag = smoothstep(0.70, 0.88, dRot.y);
        env *= (1.0 - 0.70 * topFlag);
    } else {
        // Backlit mode (uLightMode == 3): controlled rear scrim + dark front negative fill
        env *= 0.48;
        vec3 bDir = normalize(vec3(-0.15, 0.36, -0.92));
        float backScrim = smoothstep(0.72, 0.88, max(dot(dRot, bDir), 0.0));
        env += vec3(0.98, 0.99, 1.0) * backScrim * 2.4;

        // Top edge kicker
        vec3 tDir = normalize(vec3(0.35, 0.82, -0.45));
        float topKick = smoothstep(0.84, 0.95, max(dot(dRot, tDir), 0.0));
        env += vec3(0.92, 0.96, 1.0) * topKick * 1.4;

        // Subtle front bounce card so front spangles stay legible (0% black)
        vec3 frontBounce = normalize(vec3(-0.35, 0.22, 0.91));
        float fb = smoothstep(0.76, 0.92, max(dot(dRot, frontBounce), 0.0));
        env += vec3(0.88, 0.91, 0.95) * fb * 0.75;
    }

    // Ground bounce contribution below horizon
    float below = smoothstep(0.05, -0.25, d.y);
    vec3 groundBounce = (uLightMode == 1) ? vec3(0.055) : vec3(0.05, 0.053, 0.058);
    env = mix(env, groundBounce, below * 0.82);

    return env;
}

// -----------------------------------------------------------------------------
// GGX Microfacet PBR Helpers
// -----------------------------------------------------------------------------
float D_GGX(float NoH, float a) {
    float a2 = a * a;
    float d = (NoH * NoH) * (a2 - 1.0) + 1.0;
    return a2 / (PI * d * d + 1e-6);
}

float V_SmithGGX(float NoV, float NoL, float a) {
    float a2 = a * a;
    float gv = NoL * sqrt(NoV * NoV * (1.0 - a2) + a2);
    float gl = NoV * sqrt(NoL * NoL * (1.0 - a2) + a2);
    return 0.5 / (gv + gl + 1e-5);
}

vec3 F_Schlick(float VoH, vec3 F0) {
    float f = pow(clamp(1.0 - VoH, 0.0, 1.0), 5.0);
    return F0 + (1.0 - F0) * f;
}

vec3 F_SchlickRough(float NoV, vec3 F0, float rough) {
    float f = pow(clamp(1.0 - NoV, 0.0, 1.0), 5.0);
    return F0 + (max(vec3(1.0 - rough), F0) - F0) * f;
}

// Multi-sample prefiltered-like studio reflection for crisp vs satin grains
vec3 sampleStudioSpecular(vec3 R, vec3 N, float rough) {
    float r2 = rough * rough;
    vec3 c0 = evalStudioEnv(R);
    if (rough < 0.14) return c0;

    // Build orthonormal basis around R
    vec3 up = abs(R.y) < 0.95 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
    vec3 rx = normalize(cross(up, R));
    vec3 ry = cross(R, rx);

    float spread = r2 * 0.55;
    vec3 acc = c0 * 0.28;
    acc += evalStudioEnv(normalize(R + rx * spread)) * 0.14;
    acc += evalStudioEnv(normalize(R - rx * spread)) * 0.14;
    acc += evalStudioEnv(normalize(R + ry * spread)) * 0.14;
    acc += evalStudioEnv(normalize(R - ry * spread)) * 0.14;
    acc += evalStudioEnv(normalize(mix(R, N, r2 * 0.65))) * 0.16;
    return acc;
}

// -----------------------------------------------------------------------------
// Direct Light Configuration per uLightMode
// -----------------------------------------------------------------------------
void getLightRig(out vec3 L1, out vec3 C1, out vec3 L2, out vec3 C2) {
    if (uLightMode == 0) {
        L1 = normalize(vec3(-0.55, 0.72, 0.42));
        C1 = vec3(1.00, 0.985, 0.96) * 2.55;
        L2 = normalize(vec3(0.72, 0.40, 0.56));
        C2 = vec3(0.90, 0.95, 1.00) * 1.15;
    } else if (uLightMode == 1) {
        L1 = normalize(vec3(-0.55, 0.72, 0.42));
        C1 = vec3(1.0) * 2.55;
        L2 = normalize(vec3(0.72, 0.40, 0.56));
        C2 = vec3(1.0) * 1.15;
    } else if (uLightMode == 2) {
        L1 = normalize(vec3(-0.92, 0.24, 0.30));
        C1 = vec3(1.00, 0.97, 0.92) * 3.10;
        L2 = normalize(vec3(0.70, 0.48, 0.52));
        C2 = vec3(0.84, 0.91, 1.00) * 0.80;
    } else {
        L1 = normalize(vec3(-0.15, 0.38, -0.91));
        C1 = vec3(0.98, 0.99, 1.00) * 1.55;
        L2 = normalize(vec3(-0.35, 0.35, 0.87));
        C2 = vec3(0.88, 0.92, 0.96) * 0.65;
    }
}

vec3 evalDirectMetal(vec3 N, vec3 V, vec3 L, vec3 Lcol, vec3 F0, float rough, float shadow) {
    float NoL = max(dot(N, L), 0.0);
    if (NoL <= 0.0 || shadow <= 0.001) return vec3(0.0);
    vec3 H = normalize(V + L);
    float NoV = max(dot(N, V), 0.02);
    float NoH = max(dot(N, H), 0.0);
    float VoH = max(dot(V, H), 0.0);

    float a = max(rough * rough, 0.012);
    float D = D_GGX(NoH, a);
    float G = V_SmithGGX(NoV, NoL, a);
    vec3  F = F_Schlick(VoH, F0);

    // Metallic BRDF (negligible diffuse for bare zinc; subtle oxide diffuse)
    vec3 spec = (D * G) * F;
    vec3 diff = F0 * (0.045 / PI) * (1.0 - F);
    return (spec + diff) * Lcol * NoL * shadow;
}

// -----------------------------------------------------------------------------
// Studio Bench Shading (matte dark anodized slate with subtle grain & contact AO)
// -----------------------------------------------------------------------------
vec3 shadeBench(vec3 p, vec3 V) {
    vec3 N = vec3(0.0, 1.0, 0.0);

    // Subtle micro-textured matte bench surface
    float g1 = valueNoise(p.xz * 26.0);
    float g2 = valueNoise(p.xz * 110.0);
    float micro = (g1 * 0.65 + g2 * 0.35) - 0.5;

    // Slight radial studio pool vignette on the bench
    float r2 = dot(p.xz, p.xz);
    float pool = exp(-r2 * 0.16);

    vec3 baseCol = (uLightMode == 1)
        ? vec3(0.115)
        : vec3(0.105, 0.112, 0.122);
    baseCol *= (0.85 + 0.30 * pool + 0.04 * micro);

    vec3 L1, C1, L2, C2;
    getLightRig(L1, C1, L2, C2);

    float sh1 = softShadowHero(p + N * 0.014, L1, 4.5, 10.0);
    float sh2 = softShadowHero(p + N * 0.014, L2, 4.5, 7.0);
    float ao  = calcAO(p, N);

    // Direct diffuse + soft matte specular sheen
    float rough = 0.68 + 0.04 * micro;
    vec3 F0 = vec3(0.032);

    vec3 col = vec3(0.0);
    float NoL1 = max(dot(N, L1), 0.0);
    float NoL2 = max(dot(N, L2), 0.0);
    col += (baseCol / PI) * (C1 * NoL1 * sh1 + C2 * NoL2 * sh2);

    // Soft specular reflection of the studio & hero bounce (damped in backlit mode)
    vec3 H1 = normalize(V + L1);
    float a = rough * rough;
    float specDamp = (uLightMode == 3) ? 0.35 : 0.75;
    col += D_GGX(max(dot(N, H1), 0.0), a) * V_SmithGGX(max(dot(N, V), 0.02), NoL1, a)
         * F_Schlick(max(dot(V, H1), 0.0), F0) * C1 * NoL1 * sh1 * specDamp;

    // Ambient studio dome + contact occlusion
    vec3 R = reflect(-V, N);
    vec3 envDiff = evalStudioEnv(N) * 0.38 + evalStudioEnv(normalize(vec3(-0.3, 0.85, 0.3))) * 0.16;
    vec3 envSpec = sampleStudioSpecular(R, N, rough);
    vec3 kS = F_SchlickRough(max(dot(N, V), 0.02), F0, rough);
    col += (baseCol * envDiff * (1.0 - kS) + envSpec * kS * 0.35 * specDamp) * ao;

    // Subtle metallic bounce glow onto the bench near the bracket base
    float dHero = mapHero(p);
    float bounce = exp(-dHero * 3.8) * 0.08 * (0.4 + 0.6 * sh1);
    col += ((uLightMode == 1) ? vec3(0.9) : vec3(0.85, 0.90, 0.96)) * bounce;

    return col;
}

// -----------------------------------------------------------------------------
// Galvanized Zinc Bracket Shading
// -----------------------------------------------------------------------------
vec3 shadeGalvanizedBracket(vec3 p, vec3 Ngeom, vec3 V) {
    SheetFrame sf = getSheetFrame(p, Ngeom);
    SpangleData sp = evalZincSpangle(sf.uv, sf.sideId, uOpen);

    // Sharp crystal boundary groove (subtle microscopic etching where crystals meet)
    float grainBoundary = 1.0 - smoothstep(0.0, 0.028, sp.edgeDist);

    // Combine geometric normal with discrete crystal facet tilt + feathery dendritic relief
    float faceWeight = 1.0 - sf.edgeMask;
    vec2 totalTilt = sp.facetTilt * faceWeight + sp.microSlope * (0.042 * faceWeight);

    // On sheared cut edges & punched hole rims: crisp vertical shear striations
    vec3 pLoc = toBracketLocal(p);
    float shearLine = sin((pLoc.x + pLoc.y) * 260.0 + fbm2(pLoc.xz * 45.0) * 3.0);
    vec3 edgePerturb = (sf.T * shearLine * 0.045) * sf.edgeMask;

    vec3 N = normalize(Ngeom + sf.T * totalTilt.x + sf.B * totalTilt.y + edgePerturb);
    // Keep perturbed normal from flipping below grazing view
    if (dot(N, V) < 0.05) {
        N = normalize(mix(N, Ngeom, 0.65));
    }

    // Metallic F0 & roughness
    vec3 zincF0 = (uLightMode == 1)
        ? vec3(0.82)
        : sp.grainTint;

    // Abrupt reflectance jump per grain + bright sheared zinc on cut edges
    float brightFactor = mix(sp.grainBright, 0.94, sf.edgeMask);
    // Subtle dendritic shimmer across crystal faces
    brightFactor *= (0.94 + 0.12 * sp.dendrite * faceWeight);
    // Very fine dark-etched micro-line at Voronoi crystal boundary
    brightFactor *= (1.0 - 0.16 * grainBoundary * faceWeight);

    vec3 F0 = clamp(zincF0 * brightFactor, vec3(0.32), vec3(0.97));
    float rough = mix(sp.grainRough, 0.28 + 0.06 * shearLine, sf.edgeMask);
    rough = clamp(rough + 0.08 * grainBoundary * faceWeight, 0.09, 0.68);

    // Direct studio lights with hero self-shadowing
    vec3 L1, C1, L2, C2;
    getLightRig(L1, C1, L2, C2);

    float sh1 = softShadowHero(p + Ngeom * 0.014, L1, 3.5, 12.0);
    float sh2 = softShadowHero(p + Ngeom * 0.014, L2, 3.5, 8.0);
    float ao  = calcAO(p, Ngeom);

    vec3 col = vec3(0.0);
    col += evalDirectMetal(N, V, L1, C1, F0, rough, sh1);
    col += evalDirectMetal(N, V, L2, C2, F0, rough, sh2);

    // High-contrast studio environment reflection (drives the mirror-bright vs satin-dark spangle pop!)
    vec3 R = reflect(-V, N);
    float NoV = max(dot(N, V), 0.02);
    vec3 Fenv = F_SchlickRough(NoV, F0, rough);
    vec3 envSpec = sampleStudioSpecular(R, N, rough);

    // Self-reflection darkening in the concave inner corner of the L-bracket
    float selfOcc = mix(0.35, 1.0, ao);
    // Subtle diffuse zinc-oxide ambient floor so even dark-flag grains stay rich & legible
    vec3 envDiff = evalStudioEnv(N) * F0 * 0.09;

    col += (envSpec * Fenv * selfOcc + envDiff * ao);

    // Subtle edge-glint lift on the 90-deg rolled bevels & punched hole rims
    float fresnelRim = pow(1.0 - NoV, 4.0);
    col += F0 * fresnelRim * evalStudioEnv(R) * 0.14 * ao;

    return col;
}

// -----------------------------------------------------------------------------
// ACES Filmic Tone Mapping
// -----------------------------------------------------------------------------
vec3 acesToneMap(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;
    return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0);
}

// -----------------------------------------------------------------------------
// Unified Seamless Studio Backdrop (eliminates horizon seam)
// -----------------------------------------------------------------------------
vec3 evalStudioBackdrop(vec3 rd) {
    float vGrad = smoothstep(-0.15, 0.65, rd.y);
    vec3 studioWall = (uLightMode == 1)
        ? mix(vec3(0.072), vec3(0.125), vGrad)
        : mix(vec3(0.066, 0.072, 0.082), vec3(0.118, 0.126, 0.140), vGrad);
    if (uLightMode == 3) {
        studioWall *= 0.85;
    }
    return studioWall;
}

// -----------------------------------------------------------------------------
// Camera & Raymarching
// -----------------------------------------------------------------------------
void getCamera(out vec3 ro, out vec3 ta, out float fov) {
    if (uCamMode == 1) {
        // ~2.5x Macro view focused tightly on the 90-degree bend, spangles & punched hole
        ro = vec3(0.86, 0.62, 0.92);
        ta = vec3(-0.04, 0.24, 0.14);
        fov = 0.56;
    } else {
        // Hero 3/4 architectural view framing full bent L-bracket (~60% of frame) + shadow
        ro = vec3(1.68, 1.24, 1.82);
        ta = vec3(0.06, 0.46, 0.02);
        fov = 0.68;
    }
}

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

    vec3 ro, ta;
    float fov;
    getCamera(ro, ta, fov);

    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 + (1.0 / fov) * cw);

    // Raymarch scene
    float t = 0.0;
    float tMax = 14.0;
    bool hit = false;
    for (int i = 0; i < 120; i++) {
        vec3 p = ro + rd * t;
        float d = mapScene(p);
        if (d < 0.0005) {
            hit = true;
            break;
        }
        t += d * 0.92;
        if (t > tMax) break;
    }

    vec3 backdrop = evalStudioBackdrop(rd);
    vec3 col;
    if (hit) {
        vec3 p = ro + rd * t;
        float dHero = mapHero(p);
        // Rule 2: Explicit bench hit test
        bool isBench = (p.y <= dHero + 0.001);

        if (isBench) {
            col = shadeBench(p, -rd);
            // Smooth seamless studio cyclorama blend into backdrop (zero horizon seam)
            float fog = 1.0 - exp(-0.045 * t * t);
            col = mix(col, backdrop, clamp(fog, 0.0, 1.0));
        } else {
            vec3 Ngeom = calcNormalHero(p);
            col = shadeGalvanizedBracket(p, Ngeom, -rd);
        }
    } else {
        col = backdrop;
    }

    // Subtle studio vignette
    vec2 q = gl_FragCoord.xy / uResolution.xy;
    float vig = 1.0 - 0.16 * dot(q - 0.5, q - 0.5);
    col *= vig;

    // Exposure & ACES Filmic Tone Mapping (calibrated for hero lum 12-245, 0% clipped/black)
    col *= 0.98;
    col = acesToneMap(col) * 0.90;

    // Pure neutral grayscale enforcement in uLightMode == 1
    if (uLightMode == 1) {
        float lum = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = vec3(lum);
    }

    // Gamma 2.2 encoding + tiny ordered dither to prevent 8-bit banding on bench
    col = pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2));
    float dither = (hash12(gl_FragCoord.xy) - 0.5) / 255.0;
    col = clamp(col + dither, 0.0, 1.0);

    fragColor = vec4(col, 1.0);
}
