← back to Quadrille Showroom

public/proto/v13-atrium-daylight.html

647 lines

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>ATRIUM DAYLIGHT · China Seas</title>
<style>
  :root { --ink:#2b2b28; --paper:#fbf9f3; --accent:#8a7a55; }
  * { box-sizing:border-box; margin:0; padding:0; }
  html,body { height:100%; overflow:hidden; background:#eaf1f6; color:var(--ink);
    font-family:"Helvetica Neue",Helvetica,Arial,sans-serif; -webkit-font-smoothing:antialiased; }
  #app { position:fixed; inset:0; }
  canvas { display:block; }

  /* ---- masthead ---- */
  .masthead { position:fixed; top:0; left:0; right:0; z-index:20; padding:34px 30px 56px;
    pointer-events:none; text-align:center;
    background:linear-gradient(180deg, rgba(251,249,243,.9) 0%, rgba(251,249,243,0) 100%); }
  .masthead .kicker { font-size:11px; letter-spacing:.46em; text-transform:uppercase;
    color:#9a8c66; font-weight:600; }
  .masthead h1 { font-family:Georgia,"Times New Roman",serif; font-size:clamp(26px,4.4vw,46px);
    font-weight:400; letter-spacing:.1em; line-height:1; margin-top:9px; color:#34322c; }
  .masthead h1 b { font-weight:700; color:#8a7a55; }
  .masthead .sub { margin-top:10px; font-size:12px; letter-spacing:.04em; color:#6f6a5e;
    max-width:560px; margin-left:auto; margin-right:auto; }

  /* ---- focused board caption ---- */
  #caption { position:fixed; left:50%; bottom:84px; transform:translateX(-50%) translateY(14px);
    z-index:22; text-align:center; opacity:0; transition:opacity .5s, transform .5s cubic-bezier(.2,.8,.2,1);
    pointer-events:none; }
  #caption.show { opacity:1; transform:translateX(-50%) translateY(0); }
  #caption .cn { font-family:Georgia,serif; font-size:22px; letter-spacing:.01em; color:#2f2d27;
    text-shadow:0 1px 14px rgba(255,255,255,.8); }
  #caption .cc { margin-top:5px; font-size:10.5px; letter-spacing:.34em; text-transform:uppercase; color:#9a8c66; }
  #caption .cspec { margin-top:9px; font-size:11.5px; letter-spacing:.04em; color:#6a6458; }
  #caption a.cta { pointer-events:auto; display:inline-block; margin-top:14px; padding:10px 26px;
    border:1px solid rgba(138,122,85,.55); border-radius:28px; color:#6e5f3d; font-size:10.5px;
    letter-spacing:.24em; text-transform:uppercase; text-decoration:none; font-weight:700;
    background:rgba(138,122,85,.08); transition:background .15s, transform .15s; }
  #caption a.cta:hover { background:rgba(138,122,85,.2); transform:translateY(-1px); }

  .hint { position:fixed; bottom:28px; left:50%; transform:translateX(-50%); z-index:20;
    font-size:11px; letter-spacing:.3em; text-transform:uppercase; color:rgba(70,66,56,.5);
    pointer-events:none; transition:opacity .6s; }

  /* ---- FPS readout ---- */
  #fps { position:fixed; bottom:14px; right:16px; z-index:25; font:600 11px/1.3 ui-monospace,Menlo,monospace;
    color:#6e5f3d; background:rgba(255,255,255,.6); border:1px solid rgba(138,122,85,.3); border-radius:7px;
    padding:6px 10px; letter-spacing:.04em; cursor:pointer; -webkit-user-select:none; user-select:none; }
  #fps.off { opacity:.32; }

  /* ---- loading ---- */
  #boot { position:fixed; inset:0; z-index:50; display:flex; flex-direction:column;
    align-items:center; justify-content:center;
    background:linear-gradient(180deg,#dcebf4 0%, #f3f6f1 58%, #efe9da 100%); transition:opacity .9s; }
  #boot .ring { width:44px; height:44px; border-radius:50%;
    border:2px solid rgba(138,122,85,.22); border-top-color:#8a7a55; animation:spin 1s linear infinite; }
  #boot .lbl { margin-top:18px; font-size:11px; letter-spacing:.36em; text-transform:uppercase; color:#857a60; }
  @keyframes spin { to { transform:rotate(360deg); } }

  @media (max-width:720px){ .masthead .sub{display:none;} .masthead{padding-top:28px;} }
</style>
</head>
<body>
<div id="app"></div>

<div class="masthead">
  <div class="kicker">Designer Wallcoverings · The Daylight Atrium</div>
  <h1>ATRIUM <b>DAYLIGHT</b></h1>
  <div class="sub">China Seas in a glass atrium — sun pouring across pale stone, soft shafts and long
    shadows. One board steps forward at a time, full pattern edge to edge. Drag to swing the bank;
    tap a board to bring it into the light.</div>
</div>

<div id="caption">
  <div class="cn" id="cap_name">—</div>
  <div class="cc" id="cap_coll">China Seas</div>
  <div class="cspec" id="cap_spec">—</div>
  <a class="cta" id="cap_cta" href="#" target="_blank" rel="noopener noreferrer">View Pattern →</a>
</div>

<div class="hint" id="hint">drag · click a board · scroll</div>
<div id="fps" title="Toggle FPS">— fps</div>

<div id="boot"><div class="ring"></div><div class="lbl" id="bootlbl">Opening the atrium…</div></div>

<!-- r128 core (local). NOTE: r128 three.min.js has no UnrealBloomPass; this look
     relies on the bright PMREM environment for highlights, not postprocessing. -->
<script src="./three.min.js"></script>
<script>
"use strict";
(function () {
  const API = "/api/showroom/products?limit=50";
  const app = document.getElementById("app");
  const bootlbl = document.getElementById("bootlbl");
  const W = ()=>window.innerWidth, H = ()=>window.innerHeight;
  const clamp = (v,a,b)=>Math.max(a,Math.min(b,v));
  const lerp = (a,b,t)=>a+(b-a)*t;

  // -------------------------------------------------------------------------
  // RENDERER (high-end baseline)
  // -------------------------------------------------------------------------
  const renderer = new THREE.WebGLRenderer({ antialias:true, powerPreference:"high-performance" });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio||1, 2));
  renderer.setSize(W(), H());
  if ("outputColorSpace" in renderer) renderer.outputColorSpace = THREE.SRGBColorSpace;
  else if ("outputEncoding" in renderer) renderer.outputEncoding = THREE.sRGBEncoding;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.05;            // bright but held back from blow-out
  if ("physicallyCorrectLights" in renderer) renderer.physicallyCorrectLights = true;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.setClearColor(0xdfeaf2, 1);
  app.appendChild(renderer.domElement);
  const MAX_ANISO = renderer.capabilities.getMaxAnisotropy();

  const scene = new THREE.Scene();
  // airy haze for atmospheric depth — light, not murky
  scene.fog = new THREE.Fog(0xeaf1f6, 22, 58);

  const camera = new THREE.PerspectiveCamera(46, W()/H(), 0.1, 220);
  camera.position.set(0, 1.62, 9.4);
  camera.lookAt(0, 1.6, 0);

  // -------------------------------------------------------------------------
  // SKY-GRADIENT ENVIRONMENT — a procedural luminous sky dome baked through
  // PMREM so every gloss surface picks up soft daylight (IBL). Doubles as the
  // visible backdrop sky so the atrium reads as glass-open to a bright sky.
  // -------------------------------------------------------------------------
  function makeSkyTexture(){
    const c = document.createElement("canvas"); c.width = 16; c.height = 256;
    const x = c.getContext("2d");
    const g = x.createLinearGradient(0,0,0,256);
    g.addColorStop(0.00, "#bcd9ee");   // high sky — soft cyan-blue
    g.addColorStop(0.42, "#dfeaf2");   // pale horizon haze
    g.addColorStop(0.62, "#f4f1e8");   // warm light band where sun pools
    g.addColorStop(1.00, "#efe7d6");   // warm ground glow
    x.fillStyle = g; x.fillRect(0,0,16,256);
    const t = new THREE.CanvasTexture(c);
    if("colorSpace" in t) t.colorSpace = THREE.SRGBColorSpace; else t.encoding = THREE.sRGBEncoding;
    t.needsUpdate = true;
    return t;
  }
  // big inverted sky sphere as the visible backdrop
  (function buildSkyDome(){
    const tex = makeSkyTexture();
    const sky = new THREE.Mesh(
      new THREE.SphereGeometry(120, 32, 24),
      new THREE.MeshBasicMaterial({ map:tex, side:THREE.BackSide, fog:false, toneMapped:true })
    );
    scene.add(sky);
  })();
  // PMREM IBL from a bright gradient room scene → light wraps onto everything
  (function buildEnv(){
    try {
      const pmrem = new THREE.PMREMGenerator(renderer);
      // a simple bright box whose walls glow the sky palette = a daylight studio env
      const envScene = new THREE.Scene();
      const tex = makeSkyTexture();
      const dome = new THREE.Mesh(
        new THREE.SphereGeometry(40, 24, 16),
        new THREE.MeshBasicMaterial({ map:tex, side:THREE.BackSide })
      );
      envScene.add(dome);
      // a bright soft area light proxy (emissive panel) gives a hot key reflection
      const sunPanel = new THREE.Mesh(
        new THREE.PlaneGeometry(26, 26),
        new THREE.MeshBasicMaterial({ color:0xffffff })
      );
      sunPanel.position.set(10, 16, 8); sunPanel.lookAt(0,0,0);
      envScene.add(sunPanel);
      const envMap = pmrem.fromScene(envScene, 0.02).texture;
      scene.environment = envMap;
      pmrem.dispose();
    } catch(e){ /* env optional */ }
  })();

  // -------------------------------------------------------------------------
  // LIGHTING — bright, airy daylight. Strong soft sky ambient + hemisphere
  // (sky/ground bounce) + a warm low-angle SUN that throws long soft shadows
  // across the pale stone. Cool fill keeps shadows from going muddy.
  // -------------------------------------------------------------------------
  // a touch less flat ambient so the warm sun can carve real (soft) shadow depth
  scene.add(new THREE.AmbientLight(0xeaf2fb, 0.4));
  const hemi = new THREE.HemisphereLight(0xcfe4f5, 0xe9e0cd, 0.78);  // sky cyan over warm-stone bounce
  hemi.position.set(0, 20, 0);
  scene.add(hemi);

  // the SUN — warm, low and raking from upper-left so shadows stretch long & soft
  const sun = new THREE.DirectionalLight(0xfff4dc, 2.35);
  sun.position.set(-11, 8.5, 7);
  sun.castShadow = true;
  sun.shadow.mapSize.set(2048, 2048);
  sun.shadow.camera.near = 1; sun.shadow.camera.far = 50;
  sun.shadow.camera.left = -16; sun.shadow.camera.right = 16;
  sun.shadow.camera.top = 14; sun.shadow.camera.bottom = -6;
  sun.shadow.bias = -0.0004; sun.shadow.radius = 7;     // soft penumbra
  scene.add(sun);
  const sunTarget = new THREE.Object3D(); sunTarget.position.set(2, 1, -3); scene.add(sunTarget);
  sun.target = sunTarget;

  // gentle cool fill from camera-right so the shadow side still reads
  const fill = new THREE.DirectionalLight(0xbcd3ea, 0.35);
  fill.position.set(8, 5, 6); scene.add(fill);

  // -------------------------------------------------------------------------
  // ROOM — glass atrium: pale stone floor (clearcoat sheen), bright walls, a
  // mullioned glass ceiling/back that lets the sky read through.
  // -------------------------------------------------------------------------
  const FLOOR_Y = 0;

  // procedural pale-stone roughness/tint (canvas → texture, $0 local)
  function makeStoneRoughness(){
    const c = document.createElement("canvas"); c.width = c.height = 256;
    const x = c.getContext("2d");
    x.fillStyle = "#b8b8b8"; x.fillRect(0,0,256,256);
    const img = x.getImageData(0,0,256,256); const d = img.data;
    for(let i=0;i<d.length;i+=4){ const n=(Math.random()*46)|0; const v=150+n; d[i]=d[i+1]=d[i+2]=v; }
    x.putImageData(img,0,0);
    // faint slab seams (limestone tiles) — slightly rougher grout lines
    x.strokeStyle = "rgba(90,90,90,0.5)"; x.lineWidth = 2;
    for(let i=0;i<=256;i+=64){ x.beginPath(); x.moveTo(i,0); x.lineTo(i,256); x.stroke();
      x.beginPath(); x.moveTo(0,i); x.lineTo(256,i); x.stroke(); }
    const t = new THREE.CanvasTexture(c); t.anisotropy = MAX_ANISO; return t;
  }
  function makeStoneColor(){
    const c = document.createElement("canvas"); c.width = c.height = 256;
    const x = c.getContext("2d");
    x.fillStyle = "#ece7da"; x.fillRect(0,0,256,256);   // warm pale limestone
    const img = x.getImageData(0,0,256,256); const d = img.data;
    for(let i=0;i<d.length;i+=4){ const n=(Math.random()*16-8)|0;
      d[i]=clamp(236+n,210,250); d[i+1]=clamp(231+n,205,248); d[i+2]=clamp(218+n,195,238); }
    x.putImageData(img,0,0);
    x.strokeStyle = "rgba(150,142,124,0.45)"; x.lineWidth = 1.5;
    for(let i=0;i<=256;i+=64){ x.beginPath(); x.moveTo(i,0); x.lineTo(i,256); x.stroke();
      x.beginPath(); x.moveTo(0,i); x.lineTo(256,i); x.stroke(); }
    const t = new THREE.CanvasTexture(c);
    if("colorSpace" in t) t.colorSpace = THREE.SRGBColorSpace; else t.encoding = THREE.sRGBEncoding;
    t.anisotropy = MAX_ANISO; return t;
  }

  (function buildRoom(){
    // PALE STONE FLOOR — clearcoat physical gives a soft daylight sheen + long
    // shadows land legibly on it. Tiled limestone color + roughness.
    const stoneCol = makeStoneColor();
    const stoneRgh = makeStoneRoughness();
    stoneCol.wrapS = stoneCol.wrapT = THREE.RepeatWrapping; stoneCol.repeat.set(10,10);
    stoneRgh.wrapS = stoneRgh.wrapT = THREE.RepeatWrapping; stoneRgh.repeat.set(10,10);
    const floorMat = new THREE.MeshPhysicalMaterial({
      map:stoneCol, roughnessMap:stoneRgh, roughness:0.62, metalness:0.0,
      clearcoat:0.35, clearcoatRoughness:0.5, envMapIntensity:0.85
    });
    const floor = new THREE.Mesh(new THREE.PlaneGeometry(80, 60), floorMat);
    floor.rotation.x = -Math.PI/2; floor.position.y = FLOOR_Y; floor.receiveShadow = true;
    scene.add(floor);

    // bright back wall — warm off-white plaster, receives the wing-bank shadow
    const wallMat = new THREE.MeshStandardMaterial({ color:0xf3efe6, roughness:0.92, metalness:0.0, envMapIntensity:0.6 });
    const back = new THREE.Mesh(new THREE.PlaneGeometry(70, 26), wallMat);
    back.position.set(0, 7, -8.2); back.receiveShadow = true; scene.add(back);

    // side walls — pale, recede toward the light
    const sideMat = new THREE.MeshStandardMaterial({ color:0xf6f3ec, roughness:0.94, metalness:0.0, envMapIntensity:0.5 });
    const left = new THREE.Mesh(new THREE.PlaneGeometry(40, 26), sideMat);
    left.position.set(-16, 7, 2); left.rotation.y = Math.PI/2; left.receiveShadow = true; scene.add(left);
    const right = left.clone(); right.position.x = 16; right.rotation.y = -Math.PI/2; scene.add(right);

    // GLASS CEILING with mullions — thin frame grid against the bright sky so the
    // atrium reads as a daylit glass roof. Mullions cast faint shadow bars too.
    const mullMat = new THREE.MeshStandardMaterial({ color:0xd8d2c4, roughness:0.5, metalness:0.3, envMapIntensity:0.8 });
    const ceilGroup = new THREE.Group();
    const span = 36, depth = 30, y = 13;
    for(let i=-span/2; i<=span/2; i+=4){
      const bar = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, depth), mullMat);
      bar.position.set(i, y, -2); ceilGroup.add(bar);
    }
    for(let j=-depth/2; j<=depth/2; j+=5){
      const bar = new THREE.Mesh(new THREE.BoxGeometry(span, 0.12, 0.12), mullMat);
      bar.position.set(0, y, j-2); ceilGroup.add(bar);
    }
    scene.add(ceilGroup);

    // a few faint floating dust motes catching the light (tiny additive points)
    const moteGeo = new THREE.BufferGeometry();
    const MOTES = 120; const pos = new Float32Array(MOTES*3);
    for(let i=0;i<MOTES;i++){
      pos[i*3]   = (Math.random()-0.5)*24;
      pos[i*3+1] = Math.random()*9 + 1;
      pos[i*3+2] = (Math.random()-0.5)*12 - 2;
    }
    moteGeo.setAttribute("position", new THREE.BufferAttribute(pos,3));
    const moteMat = new THREE.PointsMaterial({ color:0xfff6e0, size:0.045, transparent:true,
      opacity:0.5, depthWrite:false, blending:THREE.AdditiveBlending, sizeAttenuation:true });
    const motes = new THREE.Points(moteGeo, moteMat);
    scene.add(motes);
    window.__motes = motes;
  })();

  // -------------------------------------------------------------------------
  // THE WING BANK — thin pale-framed boards, ~2" apart, side swivel.
  // Same proven mechanic as the gallery build; reskinned for daylight.
  // -------------------------------------------------------------------------
  const BOARD_W = 1.46;       // ~30" wide board face
  const BOARD_H = 3.55;       // ~6' tall
  const FRAME_T = 0.045;      // thin frame border
  const FRAME_D = 0.05;       // frame depth
  const GAP = 0.10;           // ~2" between closed boards
  const PITCH = BOARD_W + GAP;
  const BANK_Z = -4.4;
  const N_TARGET = 50;

  const boards = [];
  let products = [];
  let focusIdx = 0;

  const faceGeo = new THREE.PlaneGeometry(BOARD_W, BOARD_H);
  // thin light-bronze / champagne frame (matches the bright-gallery white frames)
  const frameMat = new THREE.MeshStandardMaterial({ color:0xe8e2d3, roughness:0.42, metalness:0.55, envMapIntensity:1.0 });
  function placeholderFace(){
    return new THREE.MeshPhysicalMaterial({ color:0xf2efe7, roughness:0.6, metalness:0.0, envMapIntensity:0.5 });
  }

  function buildBoard(idx){
    const g = new THREE.Group();
    const backing = new THREE.Mesh(
      new THREE.BoxGeometry(BOARD_W + FRAME_T*1.6, BOARD_H + FRAME_T*1.6, 0.03),
      new THREE.MeshStandardMaterial({ color:0xeae6db, roughness:0.8, metalness:0.05 })
    );
    backing.position.set(BOARD_W/2, BOARD_H/2 + 0.02, -0.02);
    backing.castShadow = true; backing.receiveShadow = true;
    g.add(backing);

    const faceMat = placeholderFace();
    const face = new THREE.Mesh(faceGeo, faceMat);
    face.position.set(BOARD_W/2, BOARD_H/2 + 0.02, 0.012);
    face.castShadow = false; face.receiveShadow = true;
    face.userData.idx = idx;
    g.add(face);

    const fb = new THREE.BoxGeometry(BOARD_W + FRAME_T*2, FRAME_T, FRAME_D);
    const fv = new THREE.BoxGeometry(FRAME_T, BOARD_H + FRAME_T*2, FRAME_D);
    const top = new THREE.Mesh(fb, frameMat); top.position.set(BOARD_W/2, BOARD_H + FRAME_T/2 + 0.02, 0.02); top.castShadow = true;
    const bot = new THREE.Mesh(fb, frameMat); bot.position.set(BOARD_W/2, FRAME_T/2 + 0.02, 0.02); bot.castShadow = true;
    const lf  = new THREE.Mesh(fv, frameMat); lf.position.set(-FRAME_T/2, BOARD_H/2 + 0.02, 0.02); lf.castShadow = true;
    const rt  = new THREE.Mesh(fv, frameMat); rt.position.set(BOARD_W + FRAME_T/2, BOARD_H/2 + 0.02, 0.02); rt.castShadow = true;
    g.add(top, bot, lf, rt);

    scene.add(g);
    return { group:g, face, faceMat, idx, data:null, texLoaded:false, swivel:0, _lit:1 };
  }

  // -------------------------------------------------------------------------
  // FLOOR REFLECTION — soft mirrored clone of the featured board (subtle on
  // stone, just a hint of the pattern picked up by the polished slab).
  // -------------------------------------------------------------------------
  const reflGeo = new THREE.PlaneGeometry(BOARD_W, BOARD_H);
  const reflMat = new THREE.MeshBasicMaterial({ transparent:true, opacity:0.0, depthWrite:false, side:THREE.FrontSide });
  const reflMesh = new THREE.Mesh(reflGeo, reflMat);
  reflMesh.scale.y = -1;
  reflMesh.renderOrder = 1;
  scene.add(reflMesh);

  // -------------------------------------------------------------------------
  // TEXTURE LOADER — lazy: featured board + a window of neighbours only.
  // -------------------------------------------------------------------------
  const texCache = new Map();
  function imgURL(u){
    if(!u) return null;
    if(/cdn\.shopify\.com/.test(u) || /^\//.test(u)) return u;
    return "/api/proxy/image?url=" + encodeURIComponent(u);
  }
  function loadTexture(url){
    if(texCache.has(url)) return Promise.resolve(texCache.get(url));
    return new Promise((resolve)=>{
      const img = new Image(); img.crossOrigin = "anonymous";
      img.onload = ()=>{
        const tex = new THREE.Texture(img);
        if("colorSpace" in tex) tex.colorSpace = THREE.SRGBColorSpace; else tex.encoding = THREE.sRGBEncoding;
        tex.anisotropy = MAX_ANISO;
        tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
        tex.repeat.set(1, 1.0);          // ~one full 27" repeat across the board face
        tex.needsUpdate = true;
        texCache.set(url, tex);
        resolve(tex);
      };
      img.onerror = ()=>resolve(null);
      img.src = url;
    });
  }
  function ensureBoardTexture(b){
    if(b.texLoaded || !b.data) return;
    const url = imgURL(b.data.image || b.data.tile);
    if(!url){ b.texLoaded = true; return; }
    b.texLoaded = true;
    loadTexture(url).then(tex=>{
      if(!tex) return;
      const m = new THREE.MeshPhysicalMaterial({
        map:tex, roughness:0.55, metalness:0.0, clearcoat:0.06, clearcoatRoughness:0.6, envMapIntensity:0.55
      });
      b.face.material.dispose && b.face.material.dispose();
      b.face.material = m; b.faceMat = m;
    });
  }
  function refreshTextureWindow(){
    const WIN = 4;
    for(let i=0;i<boards.length;i++){
      if(Math.abs(i-focusIdx) <= WIN) ensureBoardTexture(boards[i]);
    }
  }

  // -------------------------------------------------------------------------
  // LAYOUT
  // -------------------------------------------------------------------------
  function arcZ(x){ return BANK_Z - Math.abs(x)*0.018; }

  // -------------------------------------------------------------------------
  // INTERACTION
  // -------------------------------------------------------------------------
  let pan = 0, targetFocus = 0;
  const ray = new THREE.Raycaster();
  const ndc = new THREE.Vector2();

  function setFocus(i){
    targetFocus = clamp(i, 0, boards.length-1);
    focusIdx = Math.round(targetFocus);
    refreshTextureWindow();
    showCaption(boards[focusIdx]);
  }

  let dragging=false, dragX=0, focusStart=0, moved=0;
  renderer.domElement.addEventListener("pointerdown",(e)=>{
    dragging=true; moved=0; dragX=e.clientX; focusStart=targetFocus;
    renderer.domElement.setPointerCapture(e.pointerId);
  });
  renderer.domElement.addEventListener("pointermove",(e)=>{
    if(!dragging) return;
    const dx = e.clientX - dragX; moved += Math.abs(dx);
    targetFocus = clamp(focusStart - dx/120, 0, boards.length-1);
    focusIdx = Math.round(targetFocus);
  });
  renderer.domElement.addEventListener("pointerup",(e)=>{
    dragging=false;
    if(moved < 6){ tryPick(e); }
    else { setFocus(Math.round(targetFocus)); }
  });
  window.addEventListener("wheel",(e)=>{
    e.preventDefault();
    const dom = (Math.abs(e.deltaX)>Math.abs(e.deltaY))?e.deltaX:e.deltaY;
    setFocus(Math.round(targetFocus) + (dom>0?1:-1));
  }, { passive:false });

  function tryPick(e){
    const r = renderer.domElement.getBoundingClientRect();
    ndc.x = ((e.clientX-r.left)/r.width)*2 - 1;
    ndc.y = -((e.clientY-r.top)/r.height)*2 + 1;
    ray.setFromCamera(ndc, camera);
    const meshes = boards.map(b=>b.face);
    const hits = ray.intersectObjects(meshes, false);
    if(hits.length){
      const idx = hits[0].object.userData.idx;
      if(idx===focusIdx){ const d=boards[idx].data; if(d && d.store_url) window.open(d.store_url,"_blank","noopener"); }
      else setFocus(idx);
    }
  }

  // -------------------------------------------------------------------------
  // CAPTION
  // -------------------------------------------------------------------------
  const capEl = document.getElementById("caption");
  function showCaption(b){
    if(!b || !b.data){ capEl.classList.remove("show"); return; }
    const d = b.data;
    document.getElementById("cap_name").textContent = d.pattern_name || d.title || "Untitled";
    document.getElementById("cap_coll").textContent = (d.collection || d.vendor || "China Seas");
    const bits = [];
    if(d.width) bits.push(`${d.width}" wide`);
    if(d.repeat) bits.push(`${d.repeat}" repeat`);
    if(d.match_type) bits.push(d.match_type);
    document.getElementById("cap_spec").textContent = bits.join("  ·  ") || "China Seas";
    const cta = document.getElementById("cap_cta");
    if(d.store_url){ cta.href = d.store_url; cta.style.display="inline-block"; }
    else cta.style.display="none";
    capEl.classList.add("show");
  }

  // -------------------------------------------------------------------------
  // RESIZE
  // -------------------------------------------------------------------------
  window.addEventListener("resize", ()=>{
    camera.aspect = W()/H(); camera.updateProjectionMatrix();
    renderer.setSize(W(), H());
  });

  // -------------------------------------------------------------------------
  // FPS readout + pause on hidden
  // -------------------------------------------------------------------------
  const fpsEl = document.getElementById("fps");
  let fpsOn = true, frames=0, fpsT0=performance.now(), fpsVal=0;
  fpsEl.addEventListener("click", ()=>{ fpsOn=!fpsOn; fpsEl.classList.toggle("off",!fpsOn); });
  let running = true;
  document.addEventListener("visibilitychange", ()=>{
    running = !document.hidden;
    if(running){ t0=performance.now(); requestAnimationFrame(tick); }
  });

  // -------------------------------------------------------------------------
  // RENDER LOOP
  // -------------------------------------------------------------------------
  let t0 = performance.now();
  function tick(now){
    if(!running) return;
    const dt = Math.min((now - t0)/1000, 0.05); t0 = now;

    pan += (targetFocus - pan) * Math.min(1, dt*7.0);
    const eased = pan;

    for(let i=0;i<boards.length;i++){
      const b = boards[i];
      const rel = i - eased;
      const openAmt = clamp(1 - Math.abs(rel)*1.35, 0, 1);

      const targetSwivel = (rel<0 ? 1 : -1) * (1-openAmt) * 1.0;
      b.swivel += (targetSwivel - b.swivel)*Math.min(1,dt*9);
      b.group.rotation.y = b.swivel;

      const slotX = rel * PITCH;
      const targetX = slotX - (BOARD_W/2) * Math.cos(b.swivel);
      const targetZ = arcZ(slotX) + openAmt*1.55;

      b.group.position.x += (targetX - b.group.position.x)*Math.min(1,dt*9);
      b.group.position.z += (targetZ - b.group.position.z)*Math.min(1,dt*9);
      b.group.position.y = 0;

      // DAYLIGHT — everything stays bright (no chiaroscuro fade). The featured
      // board is at full daylight; neighbours are only very gently cooled so the
      // eye settles on center without losing the airy, well-lit feel.
      const litTarget = 0.82 + 0.18*Math.pow(openAmt, 1.2);
      b._lit += (litTarget - b._lit)*Math.min(1,dt*6);
      if(b.faceMat){ b.faceMat.color.setScalar(b._lit); }

      const farOff = Math.abs(rel) > 8;
      b.group.visible = !farOff;
    }

    // sun + reflection track the featured board (sun follows so its long shadow
    // sweeps with whatever's open)
    const front = boards[focusIdx];
    if(front){
      const fx = front.group.position.x + BOARD_W/2;
      sunTarget.position.set(fx*0.6, 1.2, front.group.position.z - 1);
      reflMesh.visible = true;
      if(front.faceMat && front.faceMat.map){
        reflMat.map = front.faceMat.map;
        reflMat.opacity += (0.11 - reflMat.opacity)*Math.min(1,dt*5);
        reflMesh.position.set(fx, -BOARD_H/2 - 0.02, front.group.position.z + 0.02);
        reflMesh.needsUpdate = true;
      } else {
        reflMat.opacity += (0 - reflMat.opacity)*Math.min(1,dt*5);
      }
    }

    // drifting motes
    if(window.__motes){
      window.__motes.rotation.y = now*0.00004;
      window.__motes.material.opacity = 0.4 + Math.sin(now*0.0008)*0.12;
    }

    renderer.render(scene, camera);

    frames++;
    if(now - fpsT0 >= 500){
      fpsVal = Math.round(frames*1000/(now-fpsT0)); frames=0; fpsT0=now;
      if(fpsOn) fpsEl.textContent = fpsVal + " fps";
      window.__AD_FPS = fpsVal;
    }
    requestAnimationFrame(tick);
  }

  // -------------------------------------------------------------------------
  // BOOT
  // -------------------------------------------------------------------------
  let HAS_PRODUCTS = false;
  async function start(){
    try {
      const res = await fetch(API);
      const json = await res.json();
      products = (json.products||[]).slice(0, N_TARGET);
    } catch(e){
      bootlbl.textContent = "Could not reach the catalog.";
      console.error("fetch failed", e);
      return;
    }
    if(!products.length){ bootlbl.textContent = "No products returned."; return; }
    HAS_PRODUCTS = true;

    for(let i=0;i<products.length;i++){
      const b = buildBoard(i);
      b.data = products[i];
      b.group.position.set(i*PITCH, 0, BANK_Z);
      boards.push(b);
    }
    bootlbl.textContent = `Hanging ${boards.length} boards…`;

    focusIdx = Math.min(2, boards.length-1);
    pan = targetFocus = focusIdx;
    refreshTextureWindow();

    const featUrl = imgURL(boards[focusIdx].data.image || boards[focusIdx].data.tile);
    await loadTexture(featUrl).catch(()=>null);
    ensureBoardTexture(boards[focusIdx]);
    showCaption(boards[focusIdx]);

    window.__AD__ = {
      boards: ()=>boards.length,
      textured: ()=>boards.filter(b=>b.faceMat && b.faceMat.map).length,
      focus: ()=>focusIdx,
      fps: ()=>window.__AD_FPS||0,
      ready: true
    };

    finishBoot();
    requestAnimationFrame(tick);
  }

  function finishBoot(){
    const boot = document.getElementById("boot");
    boot.style.opacity = "0";
    setTimeout(()=>boot.remove(), 950);
    const hint = document.getElementById("hint");
    setTimeout(()=>{ hint.style.opacity="0"; }, 6000);
  }

  start();
})();
</script>

<script>window.PROTO_META={"key":"V13","label":"V13 — Atrium Daylight","elements":[
  {"n":1,"label":"Glass atrium — luminous sky-gradient environment, soft global illumination"},
  {"n":2,"label":"Thin champagne-framed boards, ~2\" apart on a side swivel"},
  {"n":3,"label":"Warm low sun throws long soft shadows across pale limestone"},
  {"n":4,"label":"Mullioned glass ceiling + drifting dust motes catch the light"},
  {"n":5,"label":"Click a board → carousel-shift to center → full pattern face"}
]};</script>
<script src="./proto-chrome.js"></script>
</body>
</html>