Skip to content
VibeCodeBench
Back to the app

The code

Build a Cell, Part by Part by Claude Fable 5.2

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)52.9 KB · 1,128 lines · loads cdn.jsdelivr.net/npm/three@0.149.0/build/three.min.js
Download
<!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, viewport-fit=cover">
<title>Build an Animal Cell</title>
<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;background:#050814;color:#eaf4ff;
  font-family:ui-rounded,"SF Pro Rounded","Segoe UI",system-ui,-apple-system,Roboto,Helvetica,Arial,sans-serif;
  overscroll-behavior:none;-webkit-user-select:none;user-select:none}
#app{position:fixed;left:0;top:0;right:0;bottom:0;
  background:radial-gradient(120% 90% at 50% 36%,#143866 0%,#0b1a3a 42%,#050814 100%)}
#c{position:absolute;left:0;top:0;width:100%;height:100%;display:block;touch-action:none;cursor:grab;outline:none}
#c:active{cursor:grabbing}
#lines{position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none}
#labels{position:absolute;left:0;top:0;right:0;bottom:0;pointer-events:none;overflow:hidden}
.lab{position:absolute;left:0;top:0;white-space:nowrap;font-weight:700;font-size:12px;line-height:1;
  padding:5px 9px;border-radius:999px;background:rgba(6,12,30,.8);border:1.5px solid var(--c);color:#fff;
  opacity:0;transition:opacity .3s;will-change:transform}
.lab.on{opacity:1}
.lab.big{font-size:15px;padding:7px 12px;background:var(--c);color:#06101f;box-shadow:0 0 18px var(--c)}

#top{position:absolute;left:0;right:0;top:0;display:flex;align-items:flex-start;justify-content:space-between;gap:10px;
  padding:calc(10px + env(safe-area-inset-top)) 12px 0 14px;pointer-events:none}
#top .ttl{font-size:18px;font-weight:800;letter-spacing:.01em;text-shadow:0 2px 10px rgba(0,0,0,.6)}
#hint{font-size:12.5px;color:#b9d2f0;margin-top:2px;text-shadow:0 2px 8px rgba(0,0,0,.7)}
#demoBadge{position:absolute;left:50%;top:calc(64px + env(safe-area-inset-top));transform:translateX(-50%);display:none;
  padding:7px 14px;border-radius:999px;background:rgba(255,190,77,.95);color:#201400;font-weight:800;font-size:13px;
  pointer-events:none;white-space:nowrap;box-shadow:0 4px 18px rgba(0,0,0,.4)}

button{font:inherit;color:inherit;border:0;margin:0;cursor:pointer;touch-action:manipulation}
.btn{display:flex;align-items:center;justify-content:center;gap:8px;min-height:50px;padding:0 14px;border-radius:14px;
  background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.16);font-weight:700;font-size:15px;white-space:nowrap}
.btn:active{background:rgba(255,255,255,.2)}
.sw{width:40px;height:24px;border-radius:12px;background:rgba(255,255,255,.22);position:relative;flex:none;transition:background .2s}
.sw i{position:absolute;left:3px;top:3px;width:18px;height:18px;border-radius:50%;background:#fff;transition:transform .2s}
[aria-checked="true"] .sw{background:#35d48a}
[aria-checked="true"] .sw i{transform:translateX(16px)}
#names{pointer-events:auto;min-height:46px;padding:0 12px;font-size:14px;background:rgba(8,16,38,.7)}

#panel{position:absolute;left:50%;transform:translateX(-50%);bottom:calc(8px + env(safe-area-inset-bottom));
  width:min(720px,calc(100% - 16px));padding:12px;border-radius:20px;
  background:rgba(8,16,38,.78);border:1px solid rgba(255,255,255,.13);
  -webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);box-shadow:0 10px 40px rgba(0,0,0,.45)}
#card{display:flex;gap:11px;align-items:flex-start;min-height:92px}
#card.pop .txt{animation:cardIn .35s ease-out}
@keyframes cardIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
#dot{flex:none;width:16px;height:16px;border-radius:50%;margin-top:19px;background:#7fdcff;box-shadow:0 0 12px currentColor}
.txt{flex:1;min-width:0}
#cStep{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;color:#8fb3dc}
#cName{margin:1px 0 0;font-size:20px;line-height:1.15;font-weight:800}
#cText{margin:4px 0 0;font-size:15px;line-height:1.36;color:#d3e4f8}
#cBack{display:none;flex:none;min-height:46px;padding:0 12px;font-size:13.5px;border-radius:12px}
.row{display:flex;align-items:center;gap:10px;margin-top:8px}
#play{flex:none;width:50px;height:50px;padding:0;border-radius:50%;background:#5fd4ff;color:#04203a;border:0}
#play:active{background:#9be5ff}
#count{flex:none;min-width:54px;text-align:right;font-weight:800;font-size:14px;color:#cfe6ff;font-variant-numeric:tabular-nums}
input[type=range]{-webkit-appearance:none;appearance:none;background:transparent;height:50px;flex:1;min-width:0;margin:0;cursor:pointer}
input[type=range]:focus{outline:none}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:6px;
  background:linear-gradient(90deg,#5fd4ff var(--p,0%),rgba(255,255,255,.17) var(--p,0%))}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:30px;height:30px;border-radius:50%;
  background:#fff;border:4px solid #5fd4ff;margin-top:-10px;box-shadow:0 2px 8px rgba(0,0,0,.5)}
input[type=range]::-moz-range-track{height:10px;border-radius:6px;background:rgba(255,255,255,.17)}
input[type=range]::-moz-range-progress{height:10px;border-radius:6px;background:#5fd4ff}
input[type=range]::-moz-range-thumb{width:22px;height:22px;border-radius:50%;background:#fff;border:4px solid #5fd4ff}
.btns .btn{flex:1 1 0}
#fail{position:absolute;left:0;top:0;right:0;bottom:0;display:none;align-items:center;justify-content:center;text-align:center;
  padding:30px;font-size:17px;line-height:1.5;background:#050814;z-index:20}

@media (max-width:400px){
  #cName{font-size:18px} #cText{font-size:14px} .btn{font-size:14px;padding:0 10px}
}
@media (max-height:520px) and (orientation:landscape){
  #panel{left:auto;right:8px;transform:none;top:8px;bottom:8px;width:312px;display:flex;flex-direction:column}
  #card{flex:1;min-height:0;overflow:hidden}
  #top{right:326px}
  #cText{font-size:14px}
}
</style>
</head>
<body>
<div id="app">
  <canvas id="c"></canvas>
  <svg id="lines" xmlns="http://www.w3.org/2000/svg"></svg>
  <div id="labels"></div>

  <div id="top">
    <div>
      <div class="ttl">Build an Animal Cell</div>
      <div id="hint">Watch the cell build itself, part by part</div>
    </div>
    <button id="names" class="btn" role="switch" aria-checked="true"><span class="sw"><i></i></span>Names</button>
  </div>
  <div id="demoBadge">Demo playing &middot; touch to take over</div>

  <div id="panel">
    <div id="card">
      <span id="dot"></span>
      <div class="txt">
        <div id="cStep">The start</div>
        <h2 id="cName">Cell membrane</h2>
        <p id="cText"></p>
      </div>
      <button id="cBack" class="btn">Whole cell</button>
    </div>
    <div class="row">
      <button id="play" aria-label="Play or pause the build"></button>
      <input id="scrub" type="range" min="0" max="12" step="0.01" value="0" aria-label="Scrub through the build">
      <span id="count">0 / 11</span>
    </div>
    <div class="row btns">
      <button id="cut" class="btn" role="switch" aria-checked="false"><span class="sw"><i></i></span>Cut open</button>
      <button id="rebuild" class="btn"><svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="currentColor" d="M12 5V2L7 6l5 4V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7z"/></svg>Rebuild</button>
    </div>
  </div>

  <div id="fail">This 3D cell needs WebGL and the three.js library.<br>Please check your connection or try another browser.</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/three@0.149.0/build/three.min.js"></script>
<script>
(function(){
'use strict';
const $ = function(id){ return document.getElementById(id); };
function fail(){ $('fail').style.display = 'flex'; }
if (!window.THREE){ fail(); return; }
const THREE = window.THREE;

const canvas = $('c');
let renderer;
try {
  renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true, alpha: true });
} catch (e) { fail(); return; }
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x000000, 0);
renderer.localClippingEnabled = true;

/* ---------- helpers ---------- */
const V3 = THREE.Vector3;
const PI = Math.PI;
const clamp = function(v,a,b){ return v<a?a:(v>b?b:v); };
const clamp01 = function(v){ return v<0?0:(v>1?1:v); };
const smooth = function(x){ return x*x*(3-2*x); };
const easeOutBack = function(x){ const c1=1.70158, c3=c1+1, y=x-1; return 1 + c3*y*y*y + c1*y*y; };
const wrap = function(a){ return ((a + PI) % (2*PI) + 2*PI) % (2*PI) - PI; };
function mulberry(a){ return function(){ a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
const R = mulberry(20260611);
const rnd = function(a,b){ return a + (b-a)*R(); };
function randDir(){ const y = rnd(-1,1), a = rnd(0, PI*2), r = Math.sqrt(Math.max(0,1-y*y)); return new V3(r*Math.cos(a), y, r*Math.sin(a)); }
function fibDir(i,n){ const y = 1 - 2*(i+0.5)/n, r = Math.sqrt(Math.max(0,1-y*y)), a = i*2.399963; return new V3(r*Math.cos(a), y, r*Math.sin(a)); }
function distSeg(p,a,b){ const ab = b.clone().sub(a); const tt = clamp01(p.clone().sub(a).dot(ab)/ab.lengthSq()); return a.clone().add(ab.multiplyScalar(tt)).distanceTo(p); }

/* ---------- part data ---------- */
const PARTS = [
  { name:'Cell membrane', color:0x7fdcff, css:'#7fdcff', dist:0,
    line:'The cell membrane is a thin, bendy skin that holds the whole cell together.',
    more:'It works like a gatekeeper: it lets food and water in, pushes waste out and keeps everything else outside.' },
  { name:'Nucleus', color:0x8a6be0, css:'#a98bff', dist:14,
    line:'The nucleus is the control room, where the cell keeps its DNA instructions.',
    more:'It stores DNA, the instruction book for building and running the cell. Tiny pores in its wall let messages travel out.' },
  { name:'Nucleolus', color:0xd9488f, css:'#f472b6', dist:7,
    line:'The nucleolus is a dense spot inside the nucleus where ribosomes are made.',
    more:'It builds the pieces of ribosomes, the protein-making machines, and ships them out through the pores of the nucleus.' },
  { name:'Rough ER', color:0x4f8ff5, css:'#6aa5ff', dist:17,
    line:'The rough ER is a stack of folded sheets where new proteins are built and folded.',
    more:'Ribosomes dotted on its surface feed new proteins inside, where they are folded into shape and passed on to the Golgi.' },
  { name:'Smooth ER', color:0x2fd0b0, css:'#3ee0c0', dist:9.5,
    line:'The smooth ER is a tangle of tubes that makes fats and oils for the cell.',
    more:'It has no ribosomes. It makes fats for new membranes and helps break down harmful chemicals.' },
  { name:'Ribosomes', color:0xfff0b0, css:'#fff0b0', dist:5.5,
    line:'Ribosomes are tiny machines that snap building blocks together into proteins.',
    more:'Each one reads a copy of a gene and links amino acids into a protein. Some float free, others sit on the rough ER.' },
  { name:'Golgi apparatus', color:0xffb22e, css:'#ffbe4d', dist:10,
    line:'The Golgi apparatus is the post office: it finishes proteins, packs them and sends them off.',
    more:'Proteins arrive from the ER, get finishing touches, then are sorted into vesicles and posted to where they are needed.' },
  { name:'Mitochondria', color:0xff6a4d, css:'#ff8a70', dist:7.5,
    line:'Mitochondria are power stations that turn food into energy the cell can use.',
    more:'They use sugar and oxygen to make ATP, the energy that powers almost everything the cell does.' },
  { name:'Lysosomes', color:0x67d957, css:'#7fe36f', dist:6,
    line:'Lysosomes are the recycling crew, full of enzymes that break down waste.',
    more:'They digest worn-out parts and invading germs so the useful pieces can be used again.' },
  { name:'Vesicles', color:0xff8fc4, css:'#ffa3cf', dist:5,
    line:'Vesicles are little bubbles that carry cargo from one place to another.',
    more:'They bud off the ER and Golgi, travel across the cell and merge with their target to deliver proteins and fats.' },
  { name:'Centrioles', color:0xdcd2ff, css:'#dcd2ff', dist:5.5,
    line:'Centrioles are a pair of tiny barrels that help organise the cell when it divides.',
    more:'Each barrel is made of little tubes. Together they help build the threads that pull chromosomes apart in cell division.' },
  { name:'Cytoskeleton', color:0xa8ecff, css:'#a8ecff', dist:0,
    line:'The cytoskeleton is a web of thin fibres that gives the cell its shape.',
    more:'Its fibres hold the cell in shape, help it move and work like rails that vesicles travel along.' }
];
const NP = PARTS.length;          // 12 including the membrane
const SLOT = 3.2;                 // seconds per build slot
const CUT_OFF = 12.8, CUT_Z = 0.9;

/* ---------- scene ---------- */
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(40, 1, 0.2, 400);
scene.add(camera);
scene.add(new THREE.HemisphereLight(0xcfe8ff, 0x1a1238, 0.8));
const sun = new THREE.DirectionalLight(0xffffff, 0.85); sun.position.set(6, 10, 8); scene.add(sun);
const back = new THREE.DirectionalLight(0x6a8cff, 0.4); back.position.set(-8, -4, -10); scene.add(back);
const head = new THREE.PointLight(0xffffff, 0.4, 0); camera.add(head);

const cell = new THREE.Group(); scene.add(cell);
const cutPlane = new THREE.Plane(new V3(0, 0, -1), CUT_OFF);
const CLIP = [cutPlane];

function mat(color, o){
  o = o || {};
  const m = new THREE.MeshStandardMaterial({
    color: color, roughness: o.rough !== undefined ? o.rough : 0.5, metalness: 0.05,
    side: THREE.DoubleSide, clippingPlanes: o.noClip ? null : CLIP
  });
  m.emissive = new THREE.Color(color).multiplyScalar(0.14);
  if (o.opacity !== undefined){ m.transparent = true; m.opacity = o.opacity; }
  return m;
}

const parts = PARTS.map(function(d, i){
  return { d:d, i:i, mats:[], pops:[], grows:[], insts:[], spots:[], lab:[], lastA:-1, g:-1 };
});
const pickables = [];
function tag(o, i, focus){ o.userData.part = i; if (focus) o.userData.focus = focus; pickables.push(o); return o; }
function addPop(i, o, pos, opt){
  opt = opt || {};
  o.position.copy(pos);
  parts[i].pops.push({ o:o, pos:pos.clone(), s:opt.s || 1,
    drift: opt.drift === undefined ? 0.15 : opt.drift, wob: opt.wob || 0, k: opt.k || 0,
    ph: opt.ph === undefined ? rnd(0, 6.283) : opt.ph, q: o.quaternion.clone() });
  o.visible = false;
}
function addGrow(i, mesh, k){
  parts[i].grows.push({ mesh:mesh, total: mesh.geometry.index.count, k: k || 0 });
  mesh.geometry.setDrawRange(0, 0); mesh.visible = false;
}
function setSpots(i, spots, lift, labs){
  parts[i].spots = spots;
  parts[i].lab = labs || spots.map(function(s){ return s.clone().add(new V3(0, lift || 0, 0)); });
}

/* ---------- geometry helpers ---------- */
function fixSeam(geo, ws, hs){
  const n = geo.attributes.normal, a = n.array;
  for (let iy = 0; iy <= hs; iy++){
    const i0 = iy*(ws+1)*3, i1 = (iy*(ws+1)+ws)*3;
    let x = a[i0]+a[i1], y = a[i0+1]+a[i1+1], z = a[i0+2]+a[i1+2];
    const l = Math.hypot(x, y, z) || 1; x /= l; y /= l; z /= l;
    a[i0] = a[i1] = x; a[i0+1] = a[i1+1] = y; a[i0+2] = a[i1+2] = z;
  }
  for (let ix = 0; ix <= ws; ix++){
    const tp = ix*3, bt = (hs*(ws+1)+ix)*3;
    a[tp] = 0; a[tp+1] = 1; a[tp+2] = 0;
    a[bt] = 0; a[bt+1] = -1; a[bt+2] = 0;
  }
  n.needsUpdate = true;
}
function bumpK(x, y, z, amp, f, seed){
  return 1 + amp*(Math.sin(f*x + seed)*Math.cos(f*y + seed*2) + 0.7*Math.sin(f*z + seed*3));
}
function bumpySphere(r, ws, hs, amp, f, seed){
  const g = new THREE.SphereGeometry(r, ws, hs), p = g.attributes.position.array;
  for (let i = 0; i < p.length; i += 3){
    const x = p[i]/r, y = p[i+1]/r, z = p[i+2]/r, k = bumpK(x, y, z, amp, f, seed);
    p[i] *= k; p[i+1] *= k; p[i+2] *= k;
  }
  g.computeVertexNormals(); fixSeam(g, ws, hs);
  return g;
}
/* a thin, closed, lens-like patch of a sphere shell (used for ER sheets and Golgi cisternae) */
function shellPatch(o){
  const su = o.su || 48, sv = o.sv || 20;
  const P = function(u, v, s, extra){
    const th = o.th0 + (o.th1 - o.th0)*u;
    const ph = o.ph0 + (o.ph1 - o.ph0)*v + (o.und || 0)*Math.sin(th*2.3 + o.seed);
    const edge = Math.pow(Math.max(0, Math.sin(PI*u)), 0.4)*Math.pow(Math.max(0, Math.sin(PI*v)), 0.4);
    const rr = o.r + o.wA*Math.sin(th*o.wF + o.seed*1.7)*Math.cos(ph*o.wF*0.8 + o.seed) + s*(o.thick*edge + (extra || 0));
    const c = Math.cos(ph);
    return [rr*Math.cos(th)*c, rr*Math.sin(ph), rr*Math.sin(th)*c];
  };
  const n = (su+1)*(sv+1), pos = new Float32Array(n*2*3);
  let k = 0;
  for (let s = 0; s < 2; s++) for (let i = 0; i <= su; i++) for (let j = 0; j <= sv; j++){
    const p = P(i/su, j/sv, s ? -1 : 1, 0); pos[k++] = p[0]; pos[k++] = p[1]; pos[k++] = p[2];
  }
  const idx = [];
  for (let i = 0; i < su; i++) for (let s = 0; s < 2; s++) for (let j = 0; j < sv; j++){
    const a = s*n + i*(sv+1) + j, b = a + (sv+1), c = b + 1, d = a + 1;
    if (s === 0) idx.push(a, b, d, b, c, d); else idx.push(a, d, b, b, d, c);
  }
  const g = new THREE.BufferGeometry();
  g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
  g.setIndex(idx); g.computeVertexNormals();
  return { geo:g, P:P };
}

/* ---------- 0. membrane ---------- */
const ELL = new V3(11, 9.2, 10.2);
function memRad(x, y, z, t){
  return 1 + 0.026*Math.sin(3.1*x + 1.7*y + t*0.9) + 0.022*Math.sin(4.2*y - 2.3*z - t*0.7 + 1.3)
           + 0.020*Math.sin(3.6*z + 2.9*x + t*1.1 + 2.1) + 0.012*Math.sin(7*x - 5*y + 3*z + t*1.6);
}
function fresnel(m, amt, rgb){
  const a = amt.toFixed(2);
  m.onBeforeCompile = function(sh){
    sh.fragmentShader = sh.fragmentShader.replace('#include <output_fragment>',
      'float cellFr = pow(1.0 - abs(dot(normalize(normal), normalize(vViewPosition))), 2.5);\n' +
      'outgoingLight += vec3(' + rgb + ') * cellFr * ' + a + ';\n' +
      'diffuseColor.a = clamp(diffuseColor.a + cellFr * ' + a + ', 0.0, 1.0);\n' +
      '#include <output_fragment>');
  };
  m.customProgramCacheKey = function(){ return 'cellfr-' + a + '-' + rgb; };
}
const MW = 72, MH = 48;
const memGeo = new THREE.SphereGeometry(1, MW, MH);
const memDirs = memGeo.attributes.position.array.slice();
memGeo.boundingSphere = new THREE.Sphere(new V3(0, 0, 0), 13.5);
const memOut = new THREE.MeshPhongMaterial({ color:0x8fe3ff, transparent:true, opacity:0.10, shininess:90, specular:0xffffff,
  side:THREE.FrontSide, depthWrite:false, clippingPlanes:CLIP });
memOut.emissive = new THREE.Color(0x7fdcff).multiplyScalar(0.12);
const memIn = new THREE.MeshPhongMaterial({ color:0x3f9fd0, transparent:true, opacity:0.13, shininess:30, specular:0x224466,
  side:THREE.BackSide, depthWrite:false, clippingPlanes:CLIP });
memIn.emissive = new THREE.Color(0x3f9fd0).multiplyScalar(0.12);
fresnel(memOut, 0.55, '0.55,0.90,1.00');
fresnel(memIn, 0.32, '0.35,0.70,1.00');
const memMeshOut = new THREE.Mesh(memGeo, memOut); memMeshOut.renderOrder = 4; memMeshOut.frustumCulled = false;
const memMeshIn = new THREE.Mesh(memGeo, memIn); memMeshIn.renderOrder = 1; memMeshIn.frustumCulled = false; memMeshIn.scale.setScalar(0.985);
cell.add(memMeshIn); cell.add(memMeshOut);
tag(memMeshOut, 0); tag(memMeshIn, 0);
parts[0].mats.push(memOut, memIn);
setSpots(0, [new V3(0, 0, 0)], 0, [new V3(0, 9.4, 0)]);

function updateMembrane(t){
  const p = memGeo.attributes.position.array;
  for (let i = 0; i < p.length; i += 3){
    const x = memDirs[i], y = memDirs[i+1], z = memDirs[i+2], r = memRad(x, y, z, t);
    p[i] = x*r*ELL.x; p[i+1] = y*r*ELL.y; p[i+2] = z*r*ELL.z;
  }
  memGeo.attributes.position.needsUpdate = true;
  memGeo.computeVertexNormals(); fixSeam(memGeo, MW, MH);
}

/* cut rim (shows the sliced membrane) and a faint cytoplasm face */
const RN = 96;
const rimPos = new Float32Array((RN+1)*2*3), capPos = new Float32Array((RN+2)*3);
const rimGeo = new THREE.BufferGeometry(), capGeo = new THREE.BufferGeometry();
rimGeo.setAttribute('position', new THREE.BufferAttribute(rimPos, 3));
capGeo.setAttribute('position', new THREE.BufferAttribute(capPos, 3));
(function(){
  const ri = [], ci = [];
  for (let i = 0; i < RN; i++){ const a = 2*i, b = a+1, c = a+2, d = a+3; ri.push(a, b, c, b, d, c); ci.push(0, i+1, i+2); }
  rimGeo.setIndex(ri); capGeo.setIndex(ci);
})();
const rimMat = new THREE.MeshBasicMaterial({ color:0xc4f4ff, transparent:true, opacity:0.9, side:THREE.DoubleSide, depthWrite:false });
const capMat = new THREE.MeshBasicMaterial({ color:0x5fc8ff, transparent:true, opacity:0.06, side:THREE.DoubleSide, depthWrite:false });
const rimMesh = new THREE.Mesh(rimGeo, rimMat), capMesh = new THREE.Mesh(capGeo, capMat);
rimMesh.frustumCulled = false; capMesh.frustumCulled = false; rimMesh.renderOrder = 3; capMesh.renderOrder = 3;
rimMesh.visible = false; capMesh.visible = false;
cell.add(capMesh); cell.add(rimMesh);
const rimOut = [0, 0];
function rimPoint(alpha, c, t, out){
  let beta = Math.acos(clamp(c/ELL.z, -1, 1)), x = 0, y = 0, z = 0, r = 1;
  const ca = Math.cos(alpha), sa = Math.sin(alpha);
  for (let k = 0; k < 4; k++){
    const sb = Math.sin(beta); x = sb*ca; y = sb*sa; z = Math.cos(beta);
    r = memRad(x, y, z, t);
    beta = Math.acos(clamp(c/(ELL.z*r), -1, 1));
  }
  const sb2 = Math.sin(beta);
  out[0] = sb2*ca*r*ELL.x; out[1] = sb2*sa*r*ELL.y;
}
function updateRim(t){
  const c = cutPlane.constant/cell.scale.x, zc = c - 0.03;
  capPos[0] = 0; capPos[1] = 0; capPos[2] = zc;
  for (let i = 0; i <= RN; i++){
    rimPoint(i/RN*PI*2, c, t, rimOut);
    const k = i*6, j = (i+1)*3;
    rimPos[k] = rimOut[0]; rimPos[k+1] = rimOut[1]; rimPos[k+2] = zc;
    rimPos[k+3] = rimOut[0]*0.962; rimPos[k+4] = rimOut[1]*0.962; rimPos[k+5] = zc;
    capPos[j] = rimOut[0]*0.962; capPos[j+1] = rimOut[1]*0.962; capPos[j+2] = zc;
  }
  rimGeo.attributes.position.needsUpdate = true; capGeo.attributes.position.needsUpdate = true;
}

/* floating specks in the cytoplasm */
const SPN = 220;
const spBase = new Float32Array(SPN*3), spPh = new Float32Array(SPN), spPos = new Float32Array(SPN*3);
for (let i = 0; i < SPN; i++){
  const d = randDir(), r = Math.cbrt(R())*0.82;
  spBase[i*3] = d.x*r*ELL.x; spBase[i*3+1] = d.y*r*ELL.y; spBase[i*3+2] = d.z*r*ELL.z; spPh[i] = rnd(0, 6.283);
}
spPos.set(spBase);
const spGeo = new THREE.BufferGeometry(); spGeo.setAttribute('position', new THREE.BufferAttribute(spPos, 3));
const specks = new THREE.Points(spGeo, new THREE.PointsMaterial({ color:0xbfe9ff, size:0.12, transparent:true, opacity:0.5, depthWrite:false, clippingPlanes:CLIP }));
specks.frustumCulled = false; specks.renderOrder = 2; cell.add(specks);
function updateSpecks(t){
  for (let i = 0; i < SPN; i++){
    const k = i*3, ph = spPh[i];
    spPos[k] = spBase[k] + 0.4*Math.sin(t*0.31 + ph);
    spPos[k+1] = spBase[k+1] + 0.4*Math.sin(t*0.27 + ph*1.7);
    spPos[k+2] = spBase[k+2] + 0.4*Math.cos(t*0.23 + ph*2.3);
  }
  spGeo.attributes.position.needsUpdate = true;
}

const dummy = new THREE.Object3D();

/* ---------- 1. nucleus ---------- */
const NPOS = new V3(-1.5, 0.6, -0.5);
(function(){
  const nuc = new THREE.Group();
  const nucMat = mat(0x8a6be0, { opacity:0.5, rough:0.35 });
  const env = new THREE.Mesh(bumpySphere(3.1, 48, 32, 0.012, 4.2, 1.3), nucMat);
  env.renderOrder = 2; nuc.add(env); tag(env, 1, NPOS);
  const poreMat = mat(0x4a2f9c, { rough:0.6 });
  const NPORE = 72;
  const pores = new THREE.InstancedMesh(new THREE.SphereGeometry(0.17, 8, 6), poreMat, NPORE);
  for (let i = 0; i < NPORE; i++){
    const d = fibDir(i, NPORE);
    const rr = 3.1*bumpK(d.x, d.y, d.z, 0.012, 4.2, 1.3) + 0.01;
    dummy.position.set(d.x*rr, d.y*rr, d.z*rr);
    dummy.lookAt(d.x*20, d.y*20, d.z*20);
    dummy.scale.set(1, 1, 0.35); dummy.updateMatrix();
    pores.setMatrixAt(i, dummy.matrix);
  }
  pores.frustumCulled = false; nuc.add(pores); tag(pores, 1, NPOS);
  const chrMat = mat(0x5a3fb5, { rough:0.7 });
  for (let j = 0; j < 5; j++){
    const pts = [];
    for (let n = 0; n < 6; n++) pts.push(randDir().multiplyScalar(rnd(0.8, 2.3)));
    const curve = new THREE.CatmullRomCurve3(pts, false, 'catmullrom', 0.5);
    nuc.add(new THREE.Mesh(new THREE.TubeGeometry(curve, 60, 0.085, 6, false), chrMat));
  }
  cell.add(nuc);
  addPop(1, nuc, NPOS, { drift:0.06, ph:1.0 });
  parts[1].mats.push(nucMat, poreMat, chrMat);
  setSpots(1, [NPOS.clone()], 0, [NPOS.clone().add(new V3(-0.9, 3.1, 0.2))]);
})();

/* ---------- 2. nucleolus ---------- */
const NL = NPOS.clone().add(new V3(0.5, -0.3, 0.9));
(function(){
  const m = mat(0xd9488f, { noClip:true, rough:0.75 });
  const nl = new THREE.Mesh(bumpySphere(1.05, 28, 20, 0.06, 5, 0.7), m);
  nl.userData.clip = false; tag(nl, 2, NL); cell.add(nl);
  addPop(2, nl, NL, { drift:0.06, ph:1.0 });
  parts[2].mats.push(m);
  setSpots(2, [NL.clone()], 0, [NL.clone().add(new V3(0, 0.7, 0.3))]);
})();

/* ---------- 3. rough ER (+ 5. ribosomes sitting on it) ---------- */
const erSway = new THREE.Group(); erSway.position.copy(NPOS); cell.add(erSway);
const erLayers = [];
(function(){
  const m = mat(0x4f8ff5, { rough:0.55 });
  for (let k = 0; k < 4; k++){
    const L = shellPatch({ r:3.95 + 0.72*k, th0:(-1.15 + 0.05*k)*PI, th1:(-0.04 - 0.11*k)*PI,
      ph0:-(0.80 - 0.07*k), ph1:0.72 - 0.05*k, thick:0.2, wA:0.11, wF:5, und:0.08, seed:k*1.9 + 0.4, su:64, sv:22 });
    const mesh = new THREE.Mesh(L.geo, m);
    erSway.add(mesh); tag(mesh, 3); addGrow(3, mesh, k/4);
    erLayers.push(L);
  }
  parts[3].mats.push(m);
  const q = erLayers[3].P(0.3, 0.8, 1, 0);
  setSpots(3, [new V3(q[0], q[1], q[2]).add(NPOS)], 0);
})();

/* ---------- 4. smooth ER ---------- */
const SPOS = new V3(5.0, -3.3, -2.0);
const ser = new THREE.Group(); ser.position.copy(SPOS); cell.add(ser);
(function(){
  const m = mat(0x2fd0b0, { rough:0.4 });
  for (let j = 0; j < 5; j++){
    const pts = [];
    for (let n = 0; n < 7; n++){ const d = randDir(), r = rnd(0.6, 1.45); pts.push(new V3(d.x*r*1.15, d.y*r*0.95, d.z*r)); }
    const curve = new THREE.CatmullRomCurve3(pts, true, 'catmullrom', 0.5);
    const mesh = new THREE.Mesh(new THREE.TubeGeometry(curve, 90, 0.23, 8, true), m);
    ser.add(mesh); tag(mesh, 4, SPOS); addGrow(4, mesh, j/5);
  }
  parts[4].mats.push(m);
  setSpots(4, [SPOS.clone()], 1.6);
})();

/* ---------- 5. ribosomes ---------- */
let riboF, freeBase = [], freePh = [];
(function(){
  const geo = new THREE.SphereGeometry(0.13, 8, 6);
  const m = mat(0xfff0b0, { rough:0.4 });
  const bound = [];
  for (let k = 0; k < 4; k++) for (let n = 0; n < 60; n++){
    const p = erLayers[k].P(rnd(0.05, 0.95), rnd(0.06, 0.94), R() < 0.5 ? -1 : 1, 0.085);
    bound.push(p);
  }
  for (let i = bound.length - 1; i > 0; i--){ const j = Math.floor(R()*(i+1)); const tmp = bound[i]; bound[i] = bound[j]; bound[j] = tmp; }
  const riboB = new THREE.InstancedMesh(geo, m, bound.length);
  for (let i = 0; i < bound.length; i++){
    dummy.position.set(bound[i][0], bound[i][1], bound[i][2]); dummy.rotation.set(0, 0, 0); dummy.scale.set(1, 1, 1); dummy.updateMatrix();
    riboB.setMatrixAt(i, dummy.matrix);
  }
  riboB.frustumCulled = false; riboB.count = 0; riboB.visible = false;
  erSway.add(riboB); tag(riboB, 5);
  parts[5].insts.push({ mesh:riboB, total:bound.length });

  const centres = [new V3(3.6, -1.0, 5.0), new V3(-0.6, -5.2, -4.6), new V3(5.0, 0.4, -5.4),
                   new V3(-1.0, 6.4, -1.0), new V3(-3.6, -2.6, 4.4), new V3(-5.0, 5.4, 1.6)];
  const all = [];
  for (let c = 0; c < centres.length; c++) for (let n = 0; n < 13; n++)
    all.push(centres[c].clone().add(randDir().multiplyScalar(rnd(0.15, 0.75))));
  for (let i = all.length - 1; i > 0; i--){ const j = Math.floor(R()*(i+1)); const tmp = all[i]; all[i] = all[j]; all[j] = tmp; }
  freeBase = all; freePh = all.map(function(){ return rnd(0, 6.283); });
  riboF = new THREE.InstancedMesh(geo, m, all.length);
  for (let i = 0; i < all.length; i++){
    dummy.position.copy(all[i]); dummy.updateMatrix(); riboF.setMatrixAt(i, dummy.matrix);
  }
  riboF.frustumCulled = false; riboF.count = 0; riboF.visible = false;
  cell.add(riboF); tag(riboF, 5);
  parts[5].insts.push({ mesh:riboF, total:all.length });
  parts[5].mats.push(m);
  setSpots(5, centres, 0.9);
})();
function updateFreeRibo(t){
  const n = riboF.count;
  if (!n) return;
  dummy.rotation.set(0, 0, 0); dummy.scale.set(1, 1, 1);
  for (let i = 0; i < n; i++){
    const b = freeBase[i], ph = freePh[i];
    dummy.position.set(b.x + 0.12*Math.sin(t*0.9 + ph), b.y + 0.12*Math.sin(t*0.8 + ph*1.7), b.z + 0.12*Math.cos(t*0.7 + ph*2.3));
    dummy.updateMatrix(); riboF.setMatrixAt(i, dummy.matrix);
  }
  riboF.instanceMatrix.needsUpdate = true;
}

/* ---------- 6. Golgi apparatus ---------- */
const GPOS = new V3(4.6, 3.4, -1.4);
const gol = new THREE.Group(); gol.position.copy(GPOS);
gol.quaternion.setFromUnitVectors(new V3(1, 0, 0), NPOS.clone().sub(GPOS).normalize());
cell.add(gol);
(function(){
  const RM = 3.2;
  for (let k = 0; k < 6; k++){
    const r = 2.2 + 0.4*k, ha = 1.9/r, hb = 1.5/r;
    const L = shellPatch({ r:r, th0:-ha, th1:ha, ph0:-hb, ph1:hb, thick:0.14, wA:0.04, wF:4, und:0, seed:k*2.3 + 1, su:36, sv:18 });
    L.geo.translate(-RM, 0, 0);
    const m = mat(new THREE.Color(0xffc23a).lerp(new THREE.Color(0xff8436), k/5), { rough:0.45 });
    const mesh = new THREE.Mesh(L.geo, m);
    gol.add(mesh); tag(mesh, 6, GPOS);
    addPop(6, mesh, new V3(0, 0, 0), { drift:0.02, k:k/6 });
    parts[6].mats.push(m);
  }
  setSpots(6, [GPOS.clone()], 1.7);
})();

/* ---------- 7. mitochondria ---------- */
(function(){
  const g = new THREE.CapsuleGeometry(0.6, 1.5, 8, 20), p = g.attributes.position.array;
  for (let i = 0; i < p.length; i += 3){
    const x = p[i], y = p[i+1], z = p[i+2], a = Math.atan2(z, x), k = 1 + 0.07*Math.sin(y*8 + a*2);
    p[i] = x*k + 0.16*y*y - 0.12; p[i+2] = z*k;
  }
  g.computeVertexNormals();
  const m = mat(0xff6a4d, { rough:0.45 });
  const pos = [new V3(1.2, 5.6, 3.6), new V3(-3.4, 5.9, -3.2), new V3(7.2, 0.2, -3.6), new V3(0.8, -6.0, -3.0),
               new V3(3.2, -5.0, 4.2), new V3(-6.0, -3.6, 3.0), new V3(-2.6, -1.6, 6.4)];
  const up = new V3(0, 1, 0);
  for (let j = 0; j < pos.length; j++){
    const mesh = new THREE.Mesh(g, m);
    const axis = new V3().crossVectors(pos[j], randDir()).normalize();
    mesh.quaternion.setFromUnitVectors(up, axis);
    cell.add(mesh); tag(mesh, 7, pos[j]);
    addPop(7, mesh, pos[j], { s:rnd(0.9, 1.1), drift:0.18, wob:0.12, k:j/pos.length });
  }
  parts[7].mats.push(m);
  setSpots(7, pos, 1.0);
})();

/* ---------- 8. lysosomes ---------- */
(function(){
  const g = new THREE.SphereGeometry(0.6, 20, 14), dg = new THREE.SphereGeometry(0.11, 6, 5);
  const m = mat(0x67d957, { rough:0.35 }), dm = mat(0x2f9a3a, { rough:0.6 });
  const pos = [new V3(5.6, -4.0, 3.8), new V3(-4.8, -5.4, -2.2), new V3(2.4, 6.2, -3.0),
               new V3(8.0, -1.2, 0.2), new V3(-6.8, 2.2, 3.8), new V3(0.4, -3.8, 6.2)];
  for (let j = 0; j < pos.length; j++){
    const grp = new THREE.Group();
    const body = new THREE.Mesh(g, m); grp.add(body); tag(body, 8, pos[j]);
    for (let n = 0; n < 7; n++){ const d = new THREE.Mesh(dg, dm); d.position.copy(randDir().multiplyScalar(0.57)); grp.add(d); }
    cell.add(grp);
    addPop(8, grp, pos[j], { s:rnd(0.9, 1.15), drift:0.2, wob:0.25, k:j/pos.length });
  }
  parts[8].mats.push(m, dm);
  setSpots(8, pos, 0.8);
})();

/* ---------- 9. vesicles ---------- */
(function(){
  const g = new THREE.SphereGeometry(0.34, 16, 12);
  const m = mat(0xff8fc4, { rough:0.25 });
  const out = GPOS.clone().sub(NPOS).normalize();
  const pos = [new V3(-2.0, -6.4, 1.2)];
  for (let n = 0; n < 5; n++) pos.push(GPOS.clone().add(out.clone().multiplyScalar(rnd(1.4, 1.9))).add(randDir().multiplyScalar(rnd(0.3, 0.8))));
  pos.push(new V3(1.0, 2.6, -7.2), new V3(-4.0, 2.8, 5.6), new V3(3.4, 1.0, 6.0), new V3(7.0, 2.6, 2.8), new V3(-3.6, -5.6, -3.8));
  for (let j = 0; j < pos.length; j++){
    const mesh = new THREE.Mesh(g, m);
    cell.add(mesh); tag(mesh, 9, pos[j]);
    addPop(9, mesh, pos[j], { s:rnd(0.8, 1.25), drift:0.22, k:j/pos.length });
  }
  parts[9].mats.push(m);
  setSpots(9, pos, 0.55);
})();

/* ---------- 10. centrioles ---------- */
const CN = new V3(2.8, -2.8, -0.2);
(function(){
  const cen = new THREE.Group();
  const m = mat(0xdcd2ff, { rough:0.35 });
  const inst = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.07, 0.07, 1.0, 8), m, 54);
  const mB = [new THREE.Matrix4().makeTranslation(-0.5, 0, 0),
              new THREE.Matrix4().makeRotationZ(PI/2).setPosition(0.55, -0.1, 0)];
  const lm = new THREE.Matrix4(), tm = new THREE.Matrix4();
  let ci = 0;
  for (let b = 0; b < 2; b++) for (let n = 0; n < 9; n++) for (let j = 0; j < 3; j++){
    const a = n/9*PI*2 + (j-1)*0.22, rr = 0.36 + (j-1)*0.07;
    lm.makeTranslation(rr*Math.cos(a), 0, rr*Math.sin(a));
    tm.multiplyMatrices(mB[b], lm);
    inst.setMatrixAt(ci++, tm);
  }
  inst.frustumCulled = false;
  cen.add(inst); cen.rotation.set(0.5, 0.6, 0.25);
  cell.add(cen); tag(inst, 10, CN);
  addPop(10, cen, CN, { s:1.3, drift:0.05, wob:0.06 });
  parts[10].mats.push(m);
  setSpots(10, [CN.clone()], 1.0);
})();

/* ---------- 11. cytoskeleton ---------- */
const cyto = new THREE.Group(); cell.add(cyto);
(function(){
  const m1 = mat(0xa8ecff, { rough:0.5 }), m2 = mat(0xffd9a8, { rough:0.5 });
  m1.emissive.multiplyScalar(2); m2.emissive.multiplyScalar(2);
  const ell = function(d, s){ return new V3(d.x*ELL.x*s, d.y*ELL.y*s, d.z*ELL.z*s); };
  let best = null, bestScore = -1e9, count = 0;
  const NM = 38;
  for (let i = 0; i < NM; i++){
    const d = fibDir(i, NM), E = ell(d, 0.865);
    if (distSeg(NPOS, CN, E) < 4.6) continue;
    const mid = CN.clone().lerp(E, 0.5).add(randDir().multiplyScalar(0.6));
    const curve = new THREE.QuadraticBezierCurve3(CN.clone(), mid, E);
    const mesh = new THREE.Mesh(new THREE.TubeGeometry(curve, 22, 0.05, 5, false), m1);
    cyto.add(mesh); tag(mesh, 11); addGrow(11, mesh, (count % 12)/14); count++;
    const score = -E.x*0.7 - E.y*0.5 - (E.z > 0.4 ? 100 : 0);
    if (score > bestScore){ bestScore = score; best = E; }
  }
  for (let i = 0; i < 16; i++){
    const d1 = randDir();
    const ax = new V3().crossVectors(d1, randDir()).normalize();
    const d2 = d1.clone().applyAxisAngle(ax, rnd(0.7, 1.2));
    const A = ell(d1, 0.86), B = ell(d2, 0.86), C = ell(d1.clone().add(d2).normalize(), 0.9);
    const curve = new THREE.QuadraticBezierCurve3(A, C, B);
    const mesh = new THREE.Mesh(new THREE.TubeGeometry(curve, 22, 0.04, 5, false), m2);
    cyto.add(mesh); tag(mesh, 11); addGrow(11, mesh, 0.3 + (i % 8)/12);
  }
  parts[11].mats.push(m1, m2);
  setSpots(11, [new V3(0, 0, 0)], 0, [best ? best.clone().multiplyScalar(0.97) : new V3(-6.2, -4.6, -1.5)]);
})();

/* groups that sway as a whole */
const sways = [
  { o:erSway, pos:NPOS.clone(), d:0.06, ph:1.0, pulse:0.008 },
  { o:ser, pos:SPOS.clone(), d:0.09, ph:2.4, pulse:0.02 },
  { o:gol, pos:GPOS.clone(), d:0.08, ph:4.1, pulse:0.015 },
  { o:cyto, pos:new V3(0, 0, 0), d:0, ph:0.3, pulse:0.006 }
];

/* ---------- labels ---------- */
const labelsEl = $('labels'), svg = $('lines');
const SVGNS = 'http://www.w3.org/2000/svg';
const labels = PARTS.map(function(d){
  const el = document.createElement('div');
  el.className = 'lab'; el.textContent = d.name; el.style.setProperty('--c', d.css);
  labelsEl.appendChild(el);
  const ln = document.createElementNS(SVGNS, 'line');
  ln.setAttribute('stroke', d.css); ln.setAttribute('stroke-width', '1.5'); ln.setAttribute('opacity', '0');
  const ci = document.createElementNS(SVGNS, 'circle');
  ci.setAttribute('r', '3.5'); ci.setAttribute('fill', d.css); ci.setAttribute('stroke', '#06101f'); ci.setAttribute('stroke-width', '1'); ci.setAttribute('opacity', '0');
  svg.appendChild(ln); svg.appendChild(ci);
  return { el:el, ln:ln, ci:ci, w:70, h:22, dirty:true, on:false, big:false, oy:0, ax:0, ay:0, lx:0, sy:0, ty:0, c:0 };
});

/* ---------- state ---------- */
let W = 1, H = 1, overview = 45, fit = 1, firstLayout = true, needLayout = false;
let P = 0, playing = true, selected = -1, cutOn = false, cutT = 0, namesOn = true;
let demo = false, demoT = 0, demoI = 0;
let complete = false, wasComplete = false, curIdx = 0, lastSlot = -2, completeAt = -10;
let t = 0, lastT = null, lastInteract = -100;
const amt = new Float32Array(NP);
let camAz = -0.95, camEl = 0.12, camDist = 80, gAz = -0.45, gEl = 0.22, gDist = 45;
const camTarget = new V3(0, 0, 0), gTarget = new V3(0, 0, 0);
const MIN_DIST = 3;
const maxDist = function(){ return overview*1.5; };

const panel = $('panel'), card = $('card'), scrub = $('scrub'), playBtn = $('play'), cutBtn = $('cut'),
      namesBtn = $('names'), hintEl = $('hint'), countEl = $('count');
const ICON_PAUSE = '<svg viewBox="0 0 24 24" width="24" height="24" aria-hidden="true"><rect x="5" y="4" width="5" height="16" rx="1.5" fill="currentColor"/><rect x="14" y="4" width="5" height="16" rx="1.5" fill="currentColor"/></svg>';
const ICON_PLAY = '<svg viewBox="0 0 24 24" width="24" height="24" aria-hidden="true"><path fill="currentColor" d="M7 4.5v15a1 1 0 0 0 1.52.85l12-7.5a1 1 0 0 0 0-1.7l-12-7.5A1 1 0 0 0 7 4.5z"/></svg>';
let shownPlaying = null, cardKey = '', shownCount = '', shownHint = '', shownP = -1;

function layout(){
  W = window.innerWidth || 1; H = window.innerHeight || 1;
  renderer.setSize(W, H, false);
  camera.aspect = W/H;
  const pr = panel.getBoundingClientRect();
  const topH = 60;
  const side = pr.height > H*0.7 && pr.width < W*0.6;
  let sx = 0, sy = 0, fw = 1, fv = 1;
  if (side){
    const rw = Math.max(0, W - pr.left);
    sx = Math.round(rw/2); sy = -Math.round(topH/2); fw = (W - rw)/W; fv = (H - topH)/H;
  } else {
    const bh = Math.max(0, H - pr.top);
    sy = Math.round((bh - topH)/2); fv = (H - bh - topH)/H;
  }
  fw = Math.max(0.3, fw); fv = Math.max(0.3, fv);
  camera.setViewOffset(W, H, sx, sy, W, H);
  const tv = Math.tan(camera.fov*PI/360);
  const old = overview;
  overview = Math.max(12.4/(tv*camera.aspect*fw), 10.6/(tv*fv))*1.06;
  fit = Math.max(1, 0.72/(camera.aspect*fw));
  if (firstLayout){ gDist = overview; firstLayout = false; }
  else if (selected < 0 && Math.abs(gDist - old) < 0.6) gDist = overview;
  else gDist = Math.min(gDist, maxDist());
  for (let i = 0; i < labels.length; i++) labels[i].dirty = true;
}

function pickSpot(i){
  const s = parts[i].spots;
  if (cutOn && i !== 2){
    for (let j = 0; j < s.length; j++) if (s[j].z < CUT_Z - 0.1) return s[j].clone();
  }
  return s[0].clone();
}
function selectPart(i, focus){
  if (i < 0 || i >= NP || amt[i] < 0.5) return;
  selected = i; playing = false;
  const f = focus || pickSpot(i);
  const whole = (i === 0 || i === 11);
  if (whole){ gTarget.set(0, 0, 0); gDist = i === 0 ? overview : overview*0.8; }
  else { gTarget.copy(f); gDist = clamp(PARTS[i].dist*fit, MIN_DIST, overview); }
  const cd = new V3(Math.cos(camEl)*Math.sin(camAz), Math.sin(camEl), Math.cos(camEl)*Math.cos(camAz));
  let v = cd.clone();
  if (!whole && f.length() > 3) v = f.clone().normalize().multiplyScalar(0.65).add(cd.multiplyScalar(0.35));
  if (cutOn && v.z < 0.45) v.z = 0.45;
  v.normalize();
  gEl = clamp(Math.asin(clamp(v.y, -1, 1)), -1.2, 1.2);
  gAz = camAz + wrap(Math.atan2(v.x, v.z) - camAz);
}
function deselect(){
  selected = -1; gTarget.set(0, 0, 0); gDist = overview;
}
function setCut(on){
  cutOn = !!on;
  cutBtn.setAttribute('aria-checked', cutOn ? 'true' : 'false');
  if (cutOn && selected < 0){ gEl = 0.3; gAz = camAz + wrap(0.6 - camAz); }
}
function setNames(on){
  namesOn = !!on;
  namesBtn.setAttribute('aria-checked', namesOn ? 'true' : 'false');
}
function rebuild(){
  P = 0; playing = true; lastSlot = -2; wasComplete = false; deselect();
}

function updateCard(){
  const key = selected + '|' + curIdx + '|' + (complete ? 1 : 0);
  if (key === cardKey) return;
  cardKey = key;
  let name, text, step, col, backBtn = false;
  if (selected >= 0){ const d = PARTS[selected]; name = d.name; text = d.more; step = 'What it does'; col = d.css; backBtn = true; }
  else if (complete){ name = 'Your cell is alive!'; text = 'Drag to spin it, pinch to zoom, and tap any part to fly in and read what it does.'; step = 'All 11 parts built'; col = '#ffffff'; }
  else { const d = PARTS[curIdx]; name = d.name; text = d.line; step = curIdx === 0 ? 'The start: an empty cell' : 'Part ' + curIdx + ' of 11'; col = d.css; }
  $('cStep').textContent = step; $('cName').textContent = name; $('cText').textContent = text;
  $('dot').style.background = col; $('dot').style.color = col;
  $('cBack').style.display = backBtn ? 'flex' : 'none';
  card.classList.remove('pop'); void card.offsetWidth; card.classList.add('pop');
  needLayout = true;
}

/* ---------- picking ---------- */
const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
const tv1 = new V3(), tv2 = new V3();
function shown(o){ while (o){ if (!o.visible) return false; o = o.parent; } return true; }
function tapAt(x, y){
  for (let i = 0; i < NP; i++){
    const L = labels[i];
    if (!L.on) continue;
    if (x >= L.lx - L.w/2 - 8 && x <= L.lx + L.w/2 + 8 && y >= L.sy - 8 && y <= L.sy + L.h + 8){
      selectPart(i, i === 0 || i === 11 ? null : parts[i].spots[L.c].clone());
      return;
    }
  }
  ndc.set(x/W*2 - 1, -(y/H)*2 + 1);
  ray.setFromCamera(ndc, camera);
  const hits = ray.intersectObjects(pickables, false);
  let first = null, mem = null, nlh = null;
  for (let n = 0; n < hits.length; n++){
    const h = hits[n], o = h.object, i = o.userData.part;
    if (amt[i] < 0.5 || !shown(o)) continue;
    if (o.userData.clip !== false && h.point.z > cutPlane.constant + 0.001) continue;
    if (i === 0){ if (!mem) mem = h; continue; }
    if (!first){ first = h; if (i !== 1) break; continue; }
    if (i === 2){ nlh = h; break; }
  }
  if (first && nlh) first = nlh;
  if (first){
    const o = first.object;
    selectPart(o.userData.part, o.userData.focus ? o.userData.focus.clone() : first.point.clone());
    return;
  }
  /* forgiving fallback: nearest small part on screen */
  let bi = -1, bs = null, bd = 40;
  const cs = cell.scale.x;
  for (let i = 1; i < NP - 1; i++){
    if (amt[i] < 0.5) continue;
    const sp = parts[i].spots;
    for (let j = 0; j < sp.length; j++){
      if (i !== 2 && sp[j].z*cs > cutPlane.constant) continue;
      tv1.copy(sp[j]).multiplyScalar(cs); tv2.copy(tv1).applyMatrix4(camera.matrixWorldInverse);
      if (tv2.z > -0.3) continue;
      tv1.project(camera);
      const d = Math.hypot((tv1.x*0.5 + 0.5)*W - x, (-tv1.y*0.5 + 0.5)*H - y);
      if (d < bd){ bd = d; bi = i; bs = sp[j]; }
    }
  }
  if (bi >= 0){ selectPart(bi, bs.clone()); return; }
  if (mem){ selectPart(0); return; }
  deselect();
}

/* ---------- pointer controls ---------- */
const ptrs = new Map();
let dragMoved = false, downX = 0, downY = 0, downT = 0, pinch0 = 1, pinchDist0 = 1;
function pinchLen(){
  const a = Array.from(ptrs.values());
  return Math.hypot(a[0].x - a[1].x, a[0].y - a[1].y) || 1;
}
canvas.addEventListener('pointerdown', function(e){
  try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
  ptrs.set(e.pointerId, { x:e.clientX, y:e.clientY });
  lastInteract = t;
  if (ptrs.size === 1){ downX = e.clientX; downY = e.clientY; downT = performance.now(); dragMoved = false; }
  else if (ptrs.size === 2){ dragMoved = true; pinch0 = pinchLen(); pinchDist0 = gDist; }
});
canvas.addEventListener('pointermove', function(e){
  const p = ptrs.get(e.pointerId);
  if (!p) return;
  const dx = e.clientX - p.x, dy = e.clientY - p.y;
  p.x = e.clientX; p.y = e.clientY;
  lastInteract = t;
  if (ptrs.size === 1){
    if (!dragMoved && Math.hypot(e.clientX - downX, e.clientY - downY) > 8) dragMoved = true;
    if (dragMoved){ gAz -= dx*0.0065; gEl = clamp(gEl + dy*0.0065, -1.35, 1.35); }
  } else if (ptrs.size === 2){
    gDist = clamp(pinchDist0*pinch0/pinchLen(), MIN_DIST, maxDist());
  }
});
function pointerEnd(e){
  if (!ptrs.has(e.pointerId)) return;
  ptrs.delete(e.pointerId);
  try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
  if (e.type === 'pointerup' && ptrs.size === 0 && !dragMoved && performance.now() - downT < 600) tapAt(e.clientX, e.clientY);
  if (ptrs.size >= 1) dragMoved = true;
  lastInteract = t;
}
canvas.addEventListener('pointerup', pointerEnd);
canvas.addEventListener('pointercancel', pointerEnd);
canvas.addEventListener('wheel', function(e){
  e.preventDefault();
  gDist = clamp(gDist*Math.exp(e.deltaY*0.0012), MIN_DIST, maxDist());
  lastInteract = t;
}, { passive:false });
canvas.addEventListener('contextmenu', function(e){ e.preventDefault(); });

/* ---------- UI wiring ---------- */
scrub.addEventListener('input', function(){
  P = clamp(parseFloat(scrub.value) || 0, 0, 12);
  playing = false; lastInteract = t;
  if (selected >= 0) deselect();
});
playBtn.addEventListener('click', function(){
  if (P >= 11.999){ rebuild(); return; }
  playing = !playing; lastSlot = -2;
  if (playing && selected >= 0) deselect();
});
cutBtn.addEventListener('click', function(){ setCut(!cutOn); });
namesBtn.addEventListener('click', function(){ setNames(!namesOn); });
$('rebuild').addEventListener('click', rebuild);
$('cBack').addEventListener('click', deselect);
window.addEventListener('resize', function(){ needLayout = true; });
window.addEventListener('orientationchange', function(){ needLayout = true; });

/* ---------- demo ---------- */
const DEMO = [
  [0.0, function(){ P = 0; setCut(false); setNames(true); deselect(); }],
  [11.0, function(){ selectPart(7); }],
  [13.4, function(){ deselect(); setCut(true); }],
  [15.4, function(){ selectPart(2); }],
  [17.5, function(){ deselect(); gDist = overview*0.7; }],
  [18.8, function(){ gDist = overview; setCut(false); }]
];
function startDemo(){
  demo = true; demoT = 0; demoI = 0; playing = false;
  $('demoBadge').style.display = 'block';
}
function endDemo(){
  if (!demo) return;
  demo = false;
  $('demoBadge').style.display = 'none';
  if (P < 11.999 && selected < 0){ playing = true; lastSlot = -2; }
}
function demoStep(dt){
  demoT += dt;
  if (demoT >= 20){ demoT = 0; demoI = 0; }
  while (demoI < DEMO.length && demoT >= DEMO[demoI][0]){ DEMO[demoI][1](); demoI++; }
  P = demoT < 8.5 ? 12*demoT/8.5 : 12;
  gAz += dt*(selected >= 0 ? 0.12 : 0.3);
}
['pointerdown', 'touchstart', 'mousedown', 'keydown', 'wheel'].forEach(function(ev){
  window.addEventListener(ev, function(e){ if (demo && e.isTrusted) endDemo(); }, true);
});
function isDemoUrl(){ return /#demo$/.test(String(window.location.href)); }
window.addEventListener('hashchange', function(){ if (isDemoUrl() && !demo) startDemo(); });

/* ---------- per-frame updates ---------- */
const Q = new THREE.Quaternion(), E = new THREE.Euler();
function applyPart(i, a){
  const p = parts[i];
  for (let n = 0; n < p.pops.length; n++){
    const it = p.pops[n];
    const l = clamp01((a - it.k*0.6)/0.4);
    if (l <= 0){ it.o.visible = false; continue; }
    it.o.visible = true;
    const sc = it.s*easeOutBack(l)*(1 + 0.03*Math.sin(t*1.4 + it.ph));
    it.o.scale.setScalar(Math.max(sc, 0.001));
    const d = it.drift;
    it.o.position.set(it.pos.x + d*Math.sin(t*0.5 + it.ph), it.pos.y + d*Math.sin(t*0.43 + it.ph*1.7), it.pos.z + d*Math.cos(t*0.37 + it.ph*2.3));
    if (it.wob){
      E.set(it.wob*Math.sin(t*0.4 + it.ph), it.wob*Math.sin(t*0.33 + it.ph*1.3), it.wob*Math.cos(t*0.29 + it.ph));
      it.o.quaternion.copy(it.q).multiply(Q.setFromEuler(E));
    }
  }
  if (a !== p.lastA){
    for (let n = 0; n < p.grows.length; n++){
      const g = p.grows[n];
      const l = clamp01((a - g.k*0.6)/0.4);
      const cnt = Math.floor(g.total*smooth(l)/3)*3;
      g.mesh.geometry.setDrawRange(0, cnt); g.mesh.visible = cnt > 0;
    }
    for (let n = 0; n < p.insts.length; n++){
      const s = p.insts[n], cnt = Math.floor(s.total*smooth(a));
      s.mesh.count = cnt; s.mesh.visible = cnt > 0;
    }
    p.lastA = a;
  }
}

function updateLabels(){
  const cs = cell.scale.x, list = [];
  for (let i = 0; i < NP; i++){
    const L = labels[i], p = parts[i];
    let show = amt[i] > 0.3 && (namesOn || i === curIdx || i === selected);
    let c = -1;
    if (show){
      for (let j = 0; j < p.lab.length; j++){ if (p.lab[j].z*cs < cutPlane.constant - 0.1){ c = j; break; } }
      if (c < 0) show = false;
    }
    if (show){
      tv1.copy(p.lab[c]).multiplyScalar(cs); tv2.copy(tv1).applyMatrix4(camera.matrixWorldInverse);
      if (tv2.z > -0.5) show = false;
      else {
        tv1.project(camera);
        L.ax = (tv1.x*0.5 + 0.5)*W; L.ay = (-tv1.y*0.5 + 0.5)*H;
        if (L.ax < -40 || L.ax > W + 40 || L.ay < -10 || L.ay > H + 40) show = false;
      }
    }
    const big = show && (i === selected || (selected < 0 && i === curIdx));
    if (big !== L.big){ L.big = big; L.el.classList.toggle('big', big); L.dirty = true; }
    if (show !== L.on){
      L.on = show; L.el.classList.toggle('on', show);
      L.ln.setAttribute('opacity', show ? '0.7' : '0'); L.ci.setAttribute('opacity', show ? '1' : '0');
    }
    if (!show) continue;
    if (L.dirty){ L.w = L.el.offsetWidth || 70; L.h = L.el.offsetHeight || 22; L.dirty = false; }
    L.c = c; list.push(L);
  }
  list.sort(function(a, b){ return a.ay - b.ay; });
  for (let n = 0; n < list.length; n++){
    const L = list[n];
    L.lx = clamp(L.ax, L.w/2 + 4, Math.max(L.w/2 + 4, W - L.w/2 - 4));
    const base = L.ay - 16 - L.h;
    let ly = base;
    for (let m = 0; m < n; m++){
      const B = list[m];
      if (Math.abs(L.lx - B.lx) < (L.w + B.w)/2 + 4 && ly < B.ty + B.h + 3 && ly + L.h > B.ty - 3) ly = B.ty + B.h + 3;
    }
    L.ty = ly;
    L.oy += ((ly - base) - L.oy)*0.25;
    const y = base + L.oy;
    L.sy = y;
    L.el.style.transform = 'translate3d(' + (L.lx - L.w/2).toFixed(1) + 'px,' + y.toFixed(1) + 'px,0)';
    L.ln.setAttribute('x1', L.ax.toFixed(1)); L.ln.setAttribute('y1', L.ay.toFixed(1));
    L.ln.setAttribute('x2', L.lx.toFixed(1)); L.ln.setAttribute('y2', (y + L.h/2).toFixed(1));
    L.ci.setAttribute('cx', L.ax.toFixed(1)); L.ci.setAttribute('cy', L.ay.toFixed(1));
  }
}

function frame(now){
  requestAnimationFrame(frame);
  const tn = now*0.001;
  let dt = lastT === null ? 0.016 : tn - lastT;
  lastT = tn;
  if (!(dt > 0)) dt = 0.001;
  if (dt > 0.05) dt = 0.05;
  t += dt;

  if (needLayout){ needLayout = false; layout(); }

  if (demo) demoStep(dt);
  else if (playing){ P = Math.min(12, P + dt/SLOT); if (P >= 12) playing = false; }

  complete = P >= 11.999;
  curIdx = complete ? -1 : Math.min(11, Math.floor(P));
  amt[0] = 1;
  for (let i = 1; i < NP; i++) amt[i] = clamp01((P - i)/0.6);
  if (selected > 0 && amt[selected] < 0.5) deselect();

  /* gentle camera nudges while the build plays */
  if (playing && !demo && curIdx !== lastSlot){
    lastSlot = curIdx;
    if (selected < 0){
      if (curIdx >= 1 && curIdx !== 11){ gTarget.copy(pickSpot(curIdx)).multiplyScalar(0.3); gDist = Math.min(maxDist(), overview*0.9); }
      else { gTarget.set(0, 0, 0); gDist = overview; }
    }
  }
  if (complete && !wasComplete){
    completeAt = t;
    if (selected < 0){ gTarget.set(0, 0, 0); gDist = overview; }
  }
  wasComplete = complete;

  /* slider + counters */
  if (Math.abs(P - shownP) > 0.004){
    shownP = P;
    if (Math.abs((parseFloat(scrub.value) || 0) - P) > 0.006) scrub.value = P.toFixed(2);
    scrub.style.setProperty('--p', (P/12*100).toFixed(1) + '%');
  }
  const cTxt = complete ? 'Done!' : (curIdx + ' / 11');
  if (cTxt !== shownCount){ shownCount = cTxt; countEl.textContent = cTxt; }
  const playState = playing && !complete;
  if (playState !== shownPlaying){ shownPlaying = playState; playBtn.innerHTML = playState ? ICON_PAUSE : ICON_PLAY; }
  const hTxt = demo ? 'Demo: building, orbiting, flying in and cutting open'
    : (selected >= 0 ? 'Tap another part, or go back to the whole cell'
    : (complete ? 'Drag to orbit · Pinch to zoom · Tap any part'
    : (playing ? 'Watch the cell build itself, part by part' : 'Press play, or slide to scrub through the build')));
  if (hTxt !== shownHint){ shownHint = hTxt; hintEl.textContent = hTxt; }
  updateCard();

  /* cut */
  const cg = cutOn ? 1 : 0;
  if (cutT !== cg){ cutT = cg > cutT ? Math.min(1, cutT + dt/0.9) : Math.max(0, cutT - dt/0.9); }
  cutPlane.constant = CUT_OFF + (CUT_Z - CUT_OFF)*smooth(cutT);

  /* living motion */
  const bump = Math.max(0, 1 - (t - completeAt)/0.8);
  cell.scale.setScalar(1 + 0.01*Math.sin(t*0.8) + 0.035*Math.sin(bump*PI));
  updateMembrane(t);
  updateSpecks(t);
  for (let i = 1; i < NP; i++) applyPart(i, amt[i]);
  for (let n = 0; n < sways.length; n++){
    const s = sways[n];
    s.o.position.set(s.pos.x + s.d*Math.sin(t*0.5 + s.ph), s.pos.y + s.d*Math.sin(t*0.43 + s.ph*1.7), s.pos.z + s.d*Math.cos(t*0.37 + s.ph*2.3));
    s.o.scale.setScalar(1 + s.pulse*Math.sin(t*1.1 + s.ph));
  }
  updateFreeRibo(t);
  const cutVis = cutT > 0.02 && cutPlane.constant < ELL.z*0.93;
  rimMesh.visible = cutVis; capMesh.visible = cutVis;
  if (cutVis){ updateRim(t); rimMat.opacity = 0.9*clamp01(cutT*3); capMat.opacity = 0.06*cutT; }

  /* glow: the part being built, or the selected part */
  for (let i = 0; i < NP; i++){
    let g = 0;
    if (i === selected) g = 0.55 + 0.35*Math.sin(t*5);
    else if (selected < 0 && i === curIdx && i > 0) g = 0.6*clamp01(amt[i]*3)*(1 - clamp01((P - i - 0.55)/0.4));
    const p = parts[i];
    if (Math.abs(g - p.g) > 0.004){
      p.g = g;
      for (let n = 0; n < p.mats.length; n++) p.mats[n].emissiveIntensity = 1 + g*4;
    }
  }

  /* camera */
  if (!demo && ptrs.size === 0){
    if (playing && selected < 0) gAz += dt*0.10;
    else if (t - lastInteract > 4) gAz += dt*(selected >= 0 ? 0.035 : 0.06);
  }
  const k = 1 - Math.exp(-dt*4.2);
  camAz += (gAz - camAz)*k; camEl += (gEl - camEl)*k; camDist += (gDist - camDist)*k;
  camTarget.lerp(gTarget, k);
  const ce = Math.cos(camEl);
  camera.position.set(camTarget.x + camDist*ce*Math.sin(camAz), camTarget.y + camDist*Math.sin(camEl), camTarget.z + camDist*ce*Math.cos(camAz));
  camera.lookAt(camTarget);
  camera.updateMatrixWorld();

  updateLabels();
  renderer.render(scene, camera);
}

/* ---------- start ---------- */
updateMembrane(0);
updateCard();
layout();
needLayout = true;
camDist = overview*1.7;
if (isDemoUrl()) startDemo();
requestAnimationFrame(frame);
})();
</script>
</body>
</html>