// ─────────────────────────────────────────────────────────────────────────────
// /gallery — "Version B" of the home: walk down a curving gallery corridor.
//
// The corridor bends continuously to the right and closes into a ring, so you
// only see a few works ahead before the inner wall hides the rest; after the
// last entry you are back at the entrance. Portraits hang on both walls,
// alternating sides. Scrolling (or swiping / arrow keys) walks forward.
// Clicking a work stops in front of it and turns to face it; clicking it again
// walks into the profile.
//
// Rendered with WebGL (three.js, loaded on demand) — an earlier CSS-3D version
// glitched because browsers sort hundreds of 3D layers unreliably.
//
// Geometry (top view; x right, z toward the viewer, "y" measured downward like
// CSS and flipped when handed to three.js):
//   The ring's centre is at (Rc, 0). A point at arc length s along the
//   centreline, with lateral offset l (positive = right = toward the centre):
//     a = s / Rc
//     x = Rc - (Rc - l)·cos a,   z = -(Rc - l)·sin a
//   Heading at s is (sin a, -cos a); the camera yaw is a (+ any turn of the head).
// ─────────────────────────────────────────────────────────────────────────────

const { useState: cUseState, useEffect: cUseEffect, useRef: cUseRef, useMemo: cUseMemo } = React;

const C_DEG = 180 / Math.PI;

const THREE_SRC = 'https://unpkg.com/three@0.160.0/build/three.min.js';
const THREE_SRI = 'sha384-qOkzR5Ke/XkQxuGVJ9hpFEpDlcoLtWwVYhnJf06cLIZa2vaIptSqaubivErzmD5O';
let cThreePromise = null;
function cLoadThree() {
  if (window.THREE) return Promise.resolve(window.THREE);
  if (!cThreePromise) {
    cThreePromise = new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = THREE_SRC;
      s.integrity = THREE_SRI;
      s.crossOrigin = 'anonymous';
      s.onload = () => resolve(window.THREE);
      s.onerror = () => { cThreePromise = null; reject(new Error('three.js failed to load')); };
      document.head.appendChild(s);
    });
  }
  return cThreePromise;
}

function cMeasure() {
  const vw = window.innerWidth;
  const vh = window.innerHeight;
  const H = Math.round(Math.min(vh * 0.40, vw * 0.52));   // print height (world px)
  const W = Math.round(H * 0.74);                         // print width
  return { vw, vh, H, W };
}

function cGeo(m, count) {
  const { vh, H, W } = m;
  const P = Math.round(vh * 0.62);             // eye distance (sets the field of view)
  const CW = H * 2.5;                          // corridor width
  const half = CW / 2;
  const floorY = H * 0.78;                     // eye level is y = 0 (y measured downward)
  const ceilY = -H * 1.5;
  const S = W * 1.75;                          // arc length between consecutive works (sides alternate)
  const G = CW * 1.8;                          // gap between the last work and the first (entrance)
  const C = (count - 1) * S + G;               // ring circumference (centreline)
  const Rc = C / (2 * Math.PI);
  const s0 = CW * 1.25;                        // first work, ahead of the starting point
  return { ...m, P, CW, half, floorY, ceilY, S, G, C, Rc, s0 };
}

function cPt(g, s, l) {
  const a = s / g.Rc;
  const r = g.Rc - l;
  return { x: g.Rc - r * Math.cos(a), z: -r * Math.sin(a), a };
}

const cMod = (v, n) => ((v % n) + n) % n;

// ── canvas helpers for textures ──────────────────────────────────────────────

function cGradientCanvas(w, h, stops, horizontal) {
  const cv = document.createElement('canvas');
  cv.width = w; cv.height = h;
  const ctx = cv.getContext('2d');
  const gr = horizontal ? ctx.createLinearGradient(0, 0, w, 0) : ctx.createLinearGradient(0, 0, 0, h);
  stops.forEach(([o, c]) => gr.addColorStop(o, c));
  ctx.fillStyle = gr;
  ctx.fillRect(0, 0, w, h);
  return cv;
}

function cSvgImage(svgEl) {
  return new Promise((resolve) => {
    const clone = svgEl.cloneNode(true);
    clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
    const src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(new XMLSerializer().serializeToString(clone));
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => resolve(null);
    img.src = src;
  });
}

function cUrlImage(url) {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => resolve(null);
    img.src = url;
  });
}

// Layout of a work's texture (canvas px): shadow margin, card, label underneath.
function cCardLayout(cardW) {
  const cardH = Math.round(cardW / 0.74);
  const m = Math.round(cardW * 0.09);          // margin around the card for its soft shadow
  const labelH = Math.round(cardW * 0.26);
  return { cardW, cardH, m, labelH, w: cardW + 2 * m, h: cardH + 2 * m + labelH };
}

function cDrawCard(L, work, figImg) {
  const cv = document.createElement('canvas');
  cv.width = L.w; cv.height = L.h;
  const ctx = cv.getContext('2d');
  const k = L.cardW / 512;
  // soft drop shadow
  ctx.save();
  ctx.shadowColor = 'rgba(0,0,0,0.22)';
  ctx.shadowBlur = 26 * k;
  ctx.shadowOffsetY = 12 * k;
  ctx.fillStyle = work.paper;
  ctx.fillRect(L.m, L.m, L.cardW, L.cardH);
  ctx.restore();
  ctx.fillStyle = work.paper;
  ctx.fillRect(L.m, L.m, L.cardW, L.cardH);
  // number
  ctx.fillStyle = 'rgba(26,26,26,0.5)';
  ctx.font = `${Math.round(17 * k)}px "JetBrains Mono", monospace`;
  if ('letterSpacing' in ctx) ctx.letterSpacing = `${(2 * k).toFixed(1)}px`;
  ctx.textBaseline = 'top';
  ctx.fillText(`NO. ${String(work.i + 1).padStart(2, '0')}`, L.m + L.cardW * 0.08, L.m + L.cardH * 0.06);
  if ('letterSpacing' in ctx) ctx.letterSpacing = '0px';
  // figure, standing on the bottom 9% line
  if (figImg) {
    const fh = L.cardH * 0.75;
    const fw = fh * (figImg.width / figImg.height || 0.3);
    ctx.drawImage(figImg, L.m + (L.cardW - fw) / 2, L.m + L.cardH * 0.91 - fh, fw, fh);
  }
  // wall label
  ctx.fillStyle = '#1a1a1a';
  ctx.globalAlpha = 0.85;
  ctx.textBaseline = 'alphabetic';
  if (work.person.tba) {
    ctx.fillStyle = '#9a9792';
    ctx.font = `italic ${Math.round(28 * k)}px "DM Serif Display", serif`;
    ctx.fillText('To be announced', L.m, L.m + L.cardH + L.labelH * 0.56);
  } else {
    ctx.font = `${Math.round(30 * k)}px "DM Serif Display", serif`;
    ctx.fillText(work.person.name, L.m, L.m + L.cardH + L.labelH * 0.42);
    ctx.fillStyle = '#555';
    ctx.font = `italic ${Math.round(25 * k)}px "DM Serif Display", serif`;
    ctx.fillText(work.person.role, L.m, L.m + L.cardH + L.labelH * 0.75);
  }
  ctx.globalAlpha = 1;
  return cv;
}

function cDrawWallText(w, h, logo, count) {
  const cv = document.createElement('canvas');
  cv.width = w; cv.height = h;
  const ctx = cv.getContext('2d');
  const k = w / 600;
  ctx.fillStyle = '#8a8884';
  ctx.textBaseline = 'top';
  ctx.font = `${Math.round(18 * k)}px "JetBrains Mono", monospace`;
  if ('letterSpacing' in ctx) ctx.letterSpacing = `${(2.5 * k).toFixed(1)}px`;
  ctx.fillText('VOL. 01', 0, h * 0.18);
  let y = h * 0.18 + 40 * k;
  if (logo) {
    const lh = w * (logo.height / logo.width);
    ctx.drawImage(logo, 0, y, w, lh);
    y += lh + 36 * k;
  }
  ctx.fillText('SPRING / SUMMER 2026', 0, y);
  ctx.fillText(`${count} ENTRIES — SCROLL TO WALK`, 0, y + 32 * k);
  return cv;
}

// ─────────────────────────────────────────────────────────────────────────────

function CorridorView({ onOpen, onHome }) {
  const people = window.PEOPLE || [];
  const papers = ['#eddbbf', '#F4F0E8', '#e8dfd0', '#efe6d6'];
  const N = people.length;

  const [m, setM] = cUseState(cMeasure);
  const geo = cUseMemo(() => cGeo(m, N), [m, N]);
  const [mode, setMode] = cUseState('gallery');
  const [focused, setFocused] = cUseState(null);   // index of the work we stopped at
  const [nearIdx, setNearIdx] = cUseState(-1);     // -1 = entrance
  const [entering, setEntering] = cUseState(false);
  const [failed, setFailed] = cUseState(false);
  const [hover, setHover] = cUseState(false);

  const mountRef = cUseRef(null);
  const figsRef = cUseRef(null);
  // s: arc length walked, lat: lateral offset (+ right), yaw: extra yaw on top of the heading
  const cam = cUseRef({ s: 0, lat: 0, yaw: 0, pitch: 0 });
  const tgt = cUseRef({ s: 0, lat: 0, yaw: 0 });
  const look = cUseRef({ yaw: 0, pitch: 0 });
  const focusedRef = cUseRef(null);
  focusedRef.current = focused;
  const geoRef = cUseRef(geo);
  const drag = cUseRef(null);
  const pickRef = cUseRef(null);   // (clientX, clientY) -> work index | null, set by the renderer

  const works = cUseMemo(() => people.map((p, i) => ({
    person: p, i,
    side: i % 2 === 0 ? -1 : 1,                // -1 left (outer) wall, +1 right (inner) wall
    s: geo.s0 + i * geo.S,
    paper: papers[i % papers.length],
  })), [people, geo]);
  const worksRef = cUseRef(works);
  worksRef.current = works;

  // keep the walker in the same place (relative to the works) across resizes
  cUseEffect(() => {
    const old = geoRef.current;
    if (old !== geo) {
      const r = geo.S / old.S;
      cam.current.s *= r; tgt.current.s *= r;
      cam.current.lat *= r; tgt.current.lat *= r;
      geoRef.current = geo;
    }
  }, [geo]);

  cUseEffect(() => {
    let t = 0;
    const onR = () => { clearTimeout(t); t = setTimeout(() => setM(cMeasure()), 120); };
    window.addEventListener('resize', onR);
    return () => { clearTimeout(t); window.removeEventListener('resize', onR); };
  }, []);

  // ── camera actions ──
  const unfocus = () => {
    if (focusedRef.current === null) return;
    tgt.current.yaw = 0; tgt.current.lat = 0;
    setFocused(null);
  };
  const walk = (ds) => {
    unfocus();
    tgt.current.s += ds;
  };
  // the copy of work i (one per lap of the ring) nearest to where we're heading
  const nearestS = (i) => {
    const g = geoRef.current;
    const base = works[i].s;
    const k = Math.round((tgt.current.s - base) / g.C);
    return base + k * g.C;
  };
  const focus = (i) => {
    const g = geoRef.current;
    const w = works[cMod(i, N)];
    if (!w) return;
    tgt.current.s = nearestS(w.i);
    tgt.current.yaw = w.side < 0 ? -90 : 90;
    tgt.current.lat = -w.side * g.half * 0.1;  // stand back a little so the whole work + label fits
    setFocused(w.i);
  };
  const enter = (i) => {
    const g = geoRef.current;
    const w = works[i];
    if (!w || w.person.tba) return;
    focus(i);
    tgt.current.lat = w.side * (g.half - g.H * 0.55);
    setEntering(true);
    setTimeout(() => onOpen(w.person.id), 650);
  };
  // nearest work ahead (optionally on one side: -1 left, +1 right)
  const focusNearest = (side) => {
    const g = geoRef.current;
    const cs = cam.current.s;
    let best = null, bd = Infinity;
    for (const w of works) {
      if (side && w.side !== side) continue;
      const d = cMod(w.s - cs + g.S * 0.3, g.C) - g.S * 0.3;   // distance ahead, wrapped
      const score = Math.abs(d - g.CW * 0.3);
      if (score < bd) { bd = score; best = w; }
    }
    if (best) focus(best.i);
  };

  // ── WebGL scene ──
  cUseEffect(() => {
    if (mode !== 'gallery') return;
    let disposed = false;
    let cleanup = () => {};

    cLoadThree().then(async (THREE) => {
      if (disposed) return;
      const g = geoRef.current;
      const mount = mountRef.current;
      if (!mount) return;

      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
      renderer.setPixelRatio(dpr);
      renderer.setSize(g.vw, g.vh);
      renderer.outputColorSpace = THREE.SRGBColorSpace;
      renderer.setClearColor(0xf2f2f0, 1);
      renderer.domElement.className = 'cx-canvas';
      mount.insertBefore(renderer.domElement, mount.firstChild);

      const scene = new THREE.Scene();
      scene.fog = new THREE.Fog(0xf3f3f1, g.CW * 1.2, g.CW * 6.5);
      const fov = 2 * Math.atan((g.vh / 2) / g.P) * C_DEG;
      const camera = new THREE.PerspectiveCamera(fov, g.vw / g.vh, 4, g.C * 2);
      camera.rotation.order = 'YXZ';
      const maxAniso = renderer.capabilities.getMaxAnisotropy();
      const disposables = [];
      const tex = (canvas) => {
        const t = new THREE.CanvasTexture(canvas);
        t.colorSpace = THREE.SRGBColorSpace;
        t.anisotropy = maxAniso;
        disposables.push(t);
        return t;
      };
      const add = (geom, mat) => {
        disposables.push(geom, mat);
        const mesh = new THREE.Mesh(geom, mat);
        scene.add(mesh);
        return mesh;
      };

      const wallH = g.floorY - g.ceilY;
      const wallMidY = (g.floorY + g.ceilY) / 2;
      const SEG = 360;

      // walls: one cylinder each (outer seen from inside, inner from outside)
      const wallTex = tex(cGradientCanvas(4, 512, [
        [0, '#e6e6e3'], [0.18, '#f3f3f1'], [0.55, '#f7f7f5'], [0.94, '#f1f1ef'], [0.946, '#d9d9d5'], [1, '#e2e2de'],
      ]));
      const outer = add(new THREE.CylinderGeometry(g.Rc + g.half, g.Rc + g.half, wallH, SEG, 1, true),
        new THREE.MeshBasicMaterial({ map: wallTex, side: THREE.BackSide }));
      outer.position.set(g.Rc, -wallMidY, 0);
      const inner = add(new THREE.CylinderGeometry(g.Rc - g.half, g.Rc - g.half, wallH, SEG, 1, true),
        new THREE.MeshBasicMaterial({ map: wallTex, side: THREE.FrontSide }));
      inner.position.set(g.Rc, -wallMidY, 0);

      // floor & ceiling: rings whose u coordinate runs across the corridor (outer → inner)
      const ring = (canvas, y, up) => {
        const geom = new THREE.RingGeometry(g.Rc - g.half, g.Rc + g.half, SEG, 1);
        const pos = geom.attributes.position, uv = geom.attributes.uv;
        for (let i = 0; i < pos.count; i++) {
          const r = Math.hypot(pos.getX(i), pos.getY(i));
          uv.setXY(i, (g.Rc + g.half - r) / g.CW, 0.5);
        }
        const mesh = add(geom, new THREE.MeshBasicMaterial({ map: tex(canvas), side: THREE.DoubleSide }));
        mesh.rotation.x = up ? -Math.PI / 2 : Math.PI / 2;
        mesh.position.set(g.Rc, -y, 0);
        return mesh;
      };
      ring(cGradientCanvas(512, 4, [
        [0, '#cfcdc8'], [0.18, '#dbd9d4'], [0.44, '#e3e1dc'], [0.5, '#e7e5e0'], [0.56, '#e3e1dc'], [0.82, '#dbd9d4'], [1, '#cfcdc8'],
      ], true), g.floorY, true);
      ring(cGradientCanvas(512, 4, [
        [0, '#e3e3e0'], [0.3, '#ececea'], [0.46, '#f1f1ef'], [0.475, '#ffffff'], [0.525, '#ffffff'], [0.54, '#f1f1ef'], [0.7, '#ececea'], [1, '#e3e3e0'],
      ], true), g.ceilY, false);

      // where a flat panel hangs on a wall at arc length s
      const pieceY = -g.H * 0.06;
      const hang = (mesh, s, side, width) => {
        const inset = side < 0 ? (width * width) / (8 * (g.Rc + g.half)) + 6 : 6;
        const p = cPt(g, s, side * (g.half - inset));
        mesh.position.x = p.x;
        mesh.position.z = p.z;
        mesh.rotation.y = side < 0 ? Math.PI / 2 - p.a : -Math.PI / 2 - p.a;
      };

      // render loop (starts now; works appear as their textures are ready)
      const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      let raf;
      let lastNear = null;
      let lastKey = '';
      let dirty = true;
      const tick = () => {
        const c = cam.current, t = tgt.current;
        const k = reduce ? 0.4 : 0.075;
        const lookAmt = focusedRef.current === null ? 1 : 0.25;
        c.s += (t.s - c.s) * k;
        c.lat += (t.lat - c.lat) * k;
        c.yaw += (t.yaw + look.current.yaw * lookAmt - c.yaw) * k;
        c.pitch += (look.current.pitch * lookAmt - c.pitch) * k;

        const p = cPt(g, c.s, c.lat);
        const yaw = p.a * C_DEG + c.yaw;
        camera.position.set(p.x, 0, p.z);
        camera.rotation.y = -yaw / C_DEG;
        camera.rotation.x = c.pitch / C_DEG;

        // only redraw when something moved (or a texture arrived)
        const key = `${p.x.toFixed(2)}|${p.z.toFixed(2)}|${yaw.toFixed(3)}|${c.pitch.toFixed(3)}`;
        if (dirty || key !== lastKey) { lastKey = key; dirty = false; renderer.render(scene, camera); }

        // which work is "ahead" for the caption
        const u = cMod(c.s + g.CW * 0.55 - g.s0 + g.S / 2, g.C);
        const ni = u > N * g.S ? -1 : Math.min(N - 1, Math.floor(u / g.S));
        if (ni !== lastNear) { lastNear = ni; setNearIdx(ni); }

        raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);

      cleanup = () => {
        cancelAnimationFrame(raf);
        pickRef.current = null;
        disposables.forEach((d) => d.dispose && d.dispose());
        renderer.dispose();
        if (renderer.domElement.parentNode) renderer.domElement.parentNode.removeChild(renderer.domElement);
      };

      // fonts first, so the labels baked into textures use the right faces
      try {
        await Promise.race([
          Promise.all([
            document.fonts.load('30px "DM Serif Display"'),
            document.fonts.load('italic 25px "DM Serif Display"'),
            document.fonts.load('17px "JetBrains Mono"'),
          ]),
          new Promise((r) => setTimeout(r, 2500)),
        ]);
      } catch (e) { /* fall back to whatever is available */ }
      if (disposed) return;

      // entrance wall text
      const logo = await cUrlImage('index-of-taste.svg?v=2');
      if (disposed) return;
      {
        const tw = g.W * 1.3, th = g.H * 0.9;
        const cvw = 900, cvh = Math.round(cvw * th / tw);
        const mat = new THREE.MeshBasicMaterial({ map: tex(cDrawWallText(cvw, cvh, logo, N)), transparent: true });
        const mesh = add(new THREE.PlaneGeometry(tw, th), mat);
        mesh.position.y = -pieceY;
        hang(mesh, g.s0 - g.CW * 0.55, 1, tw);
        dirty = true;
      }

      // the works
      const cardPx = g.vw < 700 ? 448 : 512;
      const L = cCardLayout(cardPx);
      const kw = g.W / L.cardW;                  // world px per canvas px
      const svgs = figsRef.current ? figsRef.current.querySelectorAll('svg') : [];
      const pickables = [];
      const ws = worksRef.current;
      for (let i = 0; i < ws.length; i++) {
        const w = ws[i];
        const img = svgs[i] ? await cSvgImage(svgs[i]) : null;
        if (disposed) return;
        const mat = new THREE.MeshBasicMaterial({ map: tex(cDrawCard(L, w, img)), transparent: true });
        const mesh = add(new THREE.PlaneGeometry(L.w * kw, L.h * kw), mat);
        // the card's centre sits at pieceY; the plane centre is offset by the label area below it
        const cardCentreFromTop = L.m + L.cardH / 2;
        mesh.position.y = -(pieceY + (L.h / 2 - cardCentreFromTop) * kw);
        hang(mesh, w.s, w.side, g.W);
        mesh.userData.i = w.i;
        pickables.push(mesh);
        dirty = true;
      }

      // picking
      const ray = new THREE.Raycaster();
      const ndc = new THREE.Vector2();
      pickRef.current = (cx, cy) => {
        ndc.set((cx / g.vw) * 2 - 1, -(cy / g.vh) * 2 + 1);
        ray.setFromCamera(ndc, camera);
        const hit = ray.intersectObjects(pickables, false)[0];
        if (!hit) return null;
        // only the card itself (not its shadow margin / label) is clickable
        const lp = hit.object.worldToLocal(hit.point.clone());
        const px = lp.x / kw + L.w / 2, py = L.h / 2 - lp.y / kw;
        const onCard = px >= L.m && px <= L.m + L.cardW && py >= L.m && py <= L.m + L.cardH;
        return onCard ? hit.object.userData.i : null;
      };
    }).catch(() => { if (!disposed) setFailed(true); });

    return () => { disposed = true; cleanup(); };
  }, [mode, geo, N]);

  // ── input ──
  cUseEffect(() => {
    if (mode !== 'gallery') return;
    const onWheel = (e) => {
      if (e.ctrlKey) return;
      e.preventDefault();
      const d = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
      walk(d * geoRef.current.S * 0.006);
    };
    const onKey = (e) => {
      const f = focusedRef.current;
      const g = geoRef.current;
      if (e.key === 'ArrowUp' || e.key === 'w' || e.key === 'W') { e.preventDefault(); walk(g.S); }
      else if (e.key === 'ArrowDown' || e.key === 's' || e.key === 'S') { e.preventDefault(); walk(-g.S); }
      else if (e.key === 'ArrowRight') { e.preventDefault(); f === null ? focusNearest(1) : focus(f + 1); }
      else if (e.key === 'ArrowLeft') { e.preventDefault(); f === null ? focusNearest(-1) : focus(f - 1); }
      else if (e.key === 'Escape') unfocus();
      else if (e.key === 'Enter') { if (f !== null) enter(f); else focusNearest(0); }
    };
    const onMove = (e) => {
      if (e.pointerType && e.pointerType !== 'mouse') return;
      look.current.yaw = (e.clientX / window.innerWidth - 0.5) * 14;
      look.current.pitch = -(e.clientY / window.innerHeight - 0.5) * 6;
      const pick = pickRef.current;
      const onCanvas = e.target && e.target.classList && e.target.classList.contains('cx-canvas');
      const over = !!(pick && onCanvas && pick(e.clientX, e.clientY) !== null);
      setHover((h) => (h === over ? h : over));
    };
    window.addEventListener('wheel', onWheel, { passive: false });
    window.addEventListener('keydown', onKey);
    window.addEventListener('pointermove', onMove);
    return () => {
      window.removeEventListener('wheel', onWheel);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('pointermove', onMove);
    };
  });

  // pointer on the stage: touch/pen swipes walk; a click/tap on a work looks closer / enters
  const onPointerDown = (e) => {
    drag.current = { y: e.clientY, x: e.clientX, moved: 0, touch: e.pointerType !== 'mouse' };
  };
  cUseEffect(() => {
    const move = (e) => {
      const d = drag.current;
      if (!d) return;
      const dy = e.clientY - d.y;
      d.moved += Math.abs(dy) + Math.abs(e.clientX - d.x);
      d.y = e.clientY; d.x = e.clientX;
      if (d.touch) walk(-dy * 2.2);
    };
    const up = (e) => {
      const d = drag.current;
      drag.current = null;
      if (!d || d.moved > 8) return;
      const pick = pickRef.current;
      const i = pick ? pick(e.clientX, e.clientY) : null;
      if (i === null) return;
      if (focusedRef.current === i) enter(i);
      else focus(i);
    };
    const cancel = () => { drag.current = null; };
    window.addEventListener('pointermove', move);
    window.addEventListener('pointerup', up);
    window.addEventListener('pointercancel', cancel);
    return () => {
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointerup', up);
      window.removeEventListener('pointercancel', cancel);
    };
  });

  // caption content
  let caption;
  const capWork = focused !== null ? works[focused] : (nearIdx >= 0 ? works[nearIdx] : null);
  if (capWork) {
    const isTba = !!capWork.person.tba;
    caption = (
      <div className="gx-caption__inner" key={`w${capWork.i}`}>
        <span className="gx-caption__eyebrow">
          No. {String(capWork.i + 1).padStart(2, '0')} — {isTba ? 'Vol. 01' : capWork.person.role}
        </span>
        <h2 className="gx-caption__title">{isTba ? 'To be announced' : capWork.person.name}</h2>
        {isTba
          ? null
          : focused !== null
            ? <button className="gx-caption__cta" onClick={() => enter(capWork.i)}>Enter the profile →</button>
            : <button className="gx-caption__cta" onClick={() => focus(capWork.i)}>Look closer →</button>}
      </div>
    );
  } else {
    caption = (
      <div className="gx-caption__inner" key="intro">
        <span className="gx-caption__eyebrow">Vol. 01 — Spring / Summer 2026</span>
        <h2 className="gx-caption__title">An Index of Taste</h2>
        <button className="gx-caption__cta" onClick={() => walk(geo.CW * 0.9)}>Walk in →</button>
      </div>
    );
  }

  const Fig = window.Figure;
  const showList = mode === 'list' || failed;

  return (
    <div className={`gx cx${entering ? ' is-entering' : ''}${focused !== null ? ' is-focused' : ''}`} data-mode={mode}>
      <header className="gx-top">
        <button className="gx-top__brand" onClick={onHome} aria-label="Index of Taste home">
          <img src="index-of-taste.svg?v=2" alt="Index of Taste" />
        </button>
        <div className="gx-toggle" role="tablist" aria-label="View">
          <button role="tab" aria-selected={!showList} className={!showList ? 'is-on' : ''} onClick={() => setMode('gallery')}>Gallery</button>
          <button role="tab" aria-selected={showList} className={showList ? 'is-on' : ''} onClick={() => setMode('list')}>List</button>
        </div>
      </header>

      {/* the figures, rendered once off-screen so they can be baked into textures */}
      <div ref={figsRef} className="cx-figsrc" aria-hidden="true">
        {Fig ? people.map((p) => <Fig key={p.id} person={p} bare />) : null}
      </div>

      {showList ? (
        <GalleryListView people={people} onOpen={onOpen} />
      ) : (
        <>
          <div
            className="cx-stage"
            ref={mountRef}
            onPointerDown={onPointerDown}
            style={{ cursor: hover ? 'pointer' : undefined }}
            role="img"
            aria-label="A curving gallery corridor with the index's portraits on both walls"
          >
            <div className="cx-vignette" aria-hidden="true" />
          </div>

          <footer className="gx-caption" aria-live="polite">{caption}</footer>

          <div className="gx-nav">
            <span className="gx-nav__hint">
              {focused !== null ? <>Click again to enter<br />Scroll to keep walking</> : <>Scroll to walk<br />Click a work to look closer</>}
            </span>
            <div className="gx-nav__btns">
              <button onClick={() => (focused === null ? walk(-geo.S) : focus(focused - 1))} aria-label="Previous">‹</button>
              <button onClick={() => (focused === null ? focusNearest(0) : focus(focused + 1))} aria-label="Next">›</button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

window.CorridorView = CorridorView;
