import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

// 手首の回転：記録の0°と3Dモデルの0°が90°ずれているので合わせる（机カメラの録画で爪と爪カメラの向きを確かめた）
window.ROLL_OFFSET = -90;
const NAMES = ['shoulder_pan', 'shoulder_lift', 'elbow_flex', 'wrist_flex', 'wrist_roll', 'gripper'];
const AHEAD = 30; // 青い道で見せる先の長さ（30コマ＝1秒）
const JUMP_RED = 3; // これより大きい跳び（度）を赤で見せる

const $ = (id) => document.getElementById(id);
const view = $('stage');
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
view.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeceef1);
const camera = new THREE.PerspectiveCamera(40, 1, 0.01, 10);
camera.up.set(0, 0, 1);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0.18, 0, 0.08);
camera.position.set(0.95, 0.22, 0.42);
controls.update();

renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
scene.add(new THREE.HemisphereLight(0xffffff, 0x9a9da3, 2.6));
const sun = new THREE.DirectionalLight(0xffffff, 2.0);
sun.position.set(0.55, 0.2, 1.1); // 部屋の天井の明かりのつもりで、ほぼ真上から
sun.target.position.set(0.22, 0, 0);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
Object.assign(sun.shadow.camera, { left: -0.6, right: 0.6, top: 0.6, bottom: -0.6, near: 0.2, far: 3 });
sun.shadow.bias = -0.0004;
scene.add(sun, sun.target);

// 白い折りたたみ机（120×60cm のつもり）。アームの台は壁側の机の端っこに置き、手前（x のプラス）へ腕を伸ばす
const DESK = { x0: -0.033, x1: 0.567, y0: -0.45, y1: 0.75, t: 0.025 }; // 台の後ろの板（x -0.031）が机の端にそろう
const desk = new THREE.Mesh(new THREE.BoxGeometry(DESK.x1 - DESK.x0, DESK.y1 - DESK.y0, DESK.t),
  new THREE.MeshStandardMaterial({ color: 0xf4f4f2, roughness: 0.9 }));
desk.position.set((DESK.x0 + DESK.x1) / 2, (DESK.y0 + DESK.y1) / 2, -DESK.t / 2);
desk.receiveShadow = true;
scene.add(desk);
// 部屋：床と奥の壁（研究室のつもり。色は落ち着いた灰）
const floorZ = -0.72;
const room = new THREE.Mesh(new THREE.PlaneGeometry(6, 6), new THREE.MeshStandardMaterial({ color: 0xd8d5cf, roughness: 0.95 }));
room.position.set(0.3, 0, floorZ);
room.receiveShadow = true;
scene.add(room);
// 机の奥の壁（アームの台のすぐ後ろ）。写真の色に寄せた明るいグレージュ
const wallMat2 = new THREE.MeshBasicMaterial({ color: 0xd9d3cb });
const wallMat3 = new THREE.MeshBasicMaterial({ color: 0xcfc9c1 });
const wallBack = new THREE.Mesh(new THREE.BoxGeometry(0.02, 6, 3), wallMat2);
wallBack.position.set(DESK.x0 - 0.03, 0, floorZ + 1.5);
scene.add(wallBack);
const wallSide = new THREE.Mesh(new THREE.BoxGeometry(6, 0.02, 3), wallMat3);
wallSide.position.set(DESK.x0 + 3, DESK.y1 + 0.6, floorZ + 1.5);
scene.add(wallSide);
const legMat = new THREE.MeshStandardMaterial({ color: 0x9a9da3, roughness: 0.5, metalness: 0.4 });
for (const [x, y] of [[DESK.x0 + 0.04, DESK.y0 + 0.04], [DESK.x0 + 0.04, DESK.y1 - 0.04], [DESK.x1 - 0.04, DESK.y0 + 0.04], [DESK.x1 - 0.04, DESK.y1 - 0.04]]) {
  const leg = new THREE.Mesh(new THREE.BoxGeometry(0.035, 0.035, -floorZ - DESK.t), legMat);
  leg.position.set(x, y, (floorZ - DESK.t) / 2);
  leg.castShadow = true;
  scene.add(leg);
}
// 机の上の薄い目盛り（5cm）
const grid = new THREE.GridHelper(0.6, 12, 0xe2e3e6, 0xebecee);
grid.rotation.x = Math.PI / 2;
grid.position.set((DESK.x0 + DESK.x1) / 2, 0, 0.0004);
scene.add(grid);

function rpyMatrix([r, p, y]) {
  return new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(r, p, y, 'ZYX'));
}
function originMatrix(xyz, rpy) {
  const m = rpyMatrix(rpy);
  m.setPosition(xyz[0], xyz[1], xyz[2]);
  return m;
}

// URDF の色の名前ごとの見た目（印刷部品は実物に合わせて白、サーボは黒）
const MATS = {
  '3d_printed': new THREE.MeshStandardMaterial({ color: 0xf1efe9, roughness: 0.7, metalness: 0 }),
  sts3215: new THREE.MeshStandardMaterial({ color: 0x1c1d21, roughness: 0.45, metalness: 0.1 }),
};
function buildRobot(rb, bin, ghostMat) {
  const geoms = {};
  for (const [name, m] of Object.entries(rb.meshes)) {
    const g = new THREE.BufferGeometry();
    g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(bin, m.p_off, m.p_n * 3), 3));
    g.setIndex(new THREE.BufferAttribute(new Uint32Array(bin, m.i_off, m.i_n), 1));
    g.computeVertexNormals();
    geoms[name] = g;
  }
  const linkObj = {};
  for (const [lname, visuals] of Object.entries(rb.links)) {
    const o = new THREE.Group();
    for (const v of visuals) {
      const mesh = new THREE.Mesh(geoms[v.mesh], ghostMat || MATS[v.mat] || MATS['3d_printed']);
      mesh.castShadow = !ghostMat;
      mesh.name = v.mesh;
      mesh.matrixAutoUpdate = false;
      mesh.matrix.copy(originMatrix(v.xyz, v.rpy));
      o.add(mesh);
    }
    linkObj[lname] = o;
  }
  const joints = {};
  for (const j of rb.joints) {
    const fixed = new THREE.Group();
    fixed.matrixAutoUpdate = false;
    fixed.matrix.copy(originMatrix(j.xyz, j.rpy));
    const mover = new THREE.Group();
    fixed.add(mover);
    mover.add(linkObj[j.child]);
    linkObj[j.parent].add(fixed);
    joints[j.name] = { ...j, mover };
  }
  const root = linkObj['base_link'];
  return { root, joints, tip: linkObj['gripper_frame_link'], grip: linkObj['gripper_link'] };
}

function setPose(robot, q) {
  for (let i = 0; i < 5; i++) {
    const j = robot.joints[NAMES[i]];
    j.mover.quaternion.setFromAxisAngle(new THREE.Vector3(...j.axis), THREE.MathUtils.degToRad(q[i] + (i === 4 ? window.ROLL_OFFSET : 0)));
  }
  // 爪：記録の値 1 で閉じ切り（約3mm）、2.4cm のブロックを持つ値 11.5 ですき間が約24mm になるよう合わせた
  const g = robot.joints.gripper;
  const a = Math.min(g.upper, Math.max(g.lower, THREE.MathUtils.degToRad(-10.5 + 1.476 * q[5])));
  g.mover.quaternion.setFromAxisAngle(new THREE.Vector3(...g.axis), a);
}
function tipOf(robot, q) {
  setPose(robot, q);
  robot.root.updateMatrixWorld(true);
  return new THREE.Vector3().setFromMatrixPosition(robot.tip.matrixWorld);
}

const [rb, bin, trials, place, ideal, idealReal] = await Promise.all([
  fetch(new URL('robot.json', import.meta.url)).then((r) => r.json()), fetch(new URL('robot_mesh.json', import.meta.url)).then((r) => r.json()).then((j) => Uint8Array.from(atob(j.b64), (c) => c.charCodeAt(0)).buffer),
  fetch(new URL('trials_all.json', import.meta.url)).then((r) => r.json()), fetch(new URL('placement.json', import.meta.url)).then((r) => r.json()),
  fetch(new URL('ideal.json', import.meta.url)).then((r) => r.json()), fetch(new URL('ideal_real.json', import.meta.url)).then((r) => r.json())]);

// 理想の道（場所ごと）を、記録と同じ形の「回」として足す。指令＝道そのもの、答えの切り替えはない
for (const [p, d] of Object.entries(ideal)) {
  // アームの形は、理想の道を実機に流して録った記録（机のカメラの録画と同じ回）。指令は理想の道
  const r = idealReal[p];
  trials[`ideal_p${p}`] = { model: '理想の動き', place: +p, result: 'success', ideal: true, fps: 30,
    state: r.state, action: r.action, chunk_id: r.state.map(() => 0), jumps: [], phases: d.phases };
  if (r.block) place.blocks[`ideal_p${p}`] = r.block;
}
// ブロックを置く5か所（その場所の実機の回の、ブロックの位置の平均）
const PLACES = {};
for (const [k, t] of Object.entries(trials)) {
  const b = place.blocks[k];
  if (!b || t.ideal) continue;
  (PLACES[t.place] ||= []).push(b);
}
for (const p of Object.keys(PLACES)) {
  const a = PLACES[p];
  PLACES[p] = [a.reduce((s, b) => s + b[0], 0) / a.length, a.reduce((s, b) => s + b[1], 0) / a.length];
}

const arm = buildRobot(rb, bin);
scene.add(arm.root);
const ghost = buildRobot(rb, bin, new THREE.MeshStandardMaterial({ color: 0x1668e3, transparent: true, opacity: 0.14, depthWrite: false }));
scene.add(ghost.root);
const calc = buildRobot(rb, bin, new THREE.MeshBasicMaterial());
// 理想の動きを重ねるときのアーム（灰の半透明。比べる相手は灰）
const idealArm = buildRobot(rb, bin, new THREE.MeshStandardMaterial({ color: 0x8d9199, transparent: true, opacity: 0.28, depthWrite: false }));
scene.add(idealArm.root);
idealArm.root.visible = false; // 計算用（描かない）

// ブロックと箱（位置は記録と机カメラから求めた値、大きさは見積もり）
const BS = 0.024; // ブロックの一辺（2.4cm）
const BW = 0.09, BH = 0.045, T = 0.003; // 箱の外寸9cm角（写真のブロックとの比からの見積もり）・高さ45mm・板の厚み
const FLOOR = T;
const BOX_TURN = THREE.MathUtils.degToRad(6.7); // 机カメラの縦横に合わせた箱の向き
const block = new THREE.Mesh(new THREE.BoxGeometry(BS, BS, BS), new THREE.MeshStandardMaterial({ color: 0xe8333c, roughness: 0.5 }));
block.rotation.z = BOX_TURN;
block.castShadow = true;
scene.add(block);
const box = new THREE.Group();
const wallMat = new THREE.MeshStandardMaterial({ color: 0xfafafa, roughness: 0.85 });
for (const [w, d, x, y] of [[BW, T, 0, (BW - T) / 2], [BW, T, 0, -(BW - T) / 2], [T, BW, (BW - T) / 2, 0], [T, BW, -(BW - T) / 2, 0]]) {
  const m = new THREE.Mesh(new THREE.BoxGeometry(w, d, BH), wallMat);
  m.position.set(x, y, BH / 2);
  m.castShadow = m.receiveShadow = true;
  box.add(m);
}
const floor = new THREE.Mesh(new THREE.BoxGeometry(BW - 2 * T, BW - 2 * T, T), new THREE.MeshStandardMaterial({ color: 0xc9cacc, roughness: 0.6, metalness: 0.2 }));
floor.position.z = T / 2;
floor.receiveShadow = true;
box.add(floor);
box.rotation.z = BOX_TURN;
box.position.set(place.box[0], place.box[1], 0);
scene.add(box);

// ブロックを置く5か所の印（机の上の薄い四角と番号）
const placeMarks = [];
for (const [p, xy] of Object.entries(PLACES)) {
  const m = new THREE.Mesh(new THREE.PlaneGeometry(BS + 0.006, BS + 0.006), new THREE.MeshBasicMaterial({ color: 0xc9ccd2, transparent: true, opacity: 0.7, depthWrite: false }));
  m.position.set(xy[0], xy[1], 0.0007);
  m.rotation.z = BOX_TURN;
  scene.add(m);
  const el = document.createElement('div');
  el.className = 'plbl';
  el.textContent = p;
  $('stage').appendChild(el);
  placeMarks.push({ p: +p, m, el, pos: new THREE.Vector3(xy[0], xy[1], 0) });
}

// 線
function makeLine(color, width) {
  const geo = new THREE.BufferGeometry();
  geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * 200), 3));
  const line = new THREE.Line(geo, new THREE.LineBasicMaterial({ color, linewidth: width, transparent: true }));
  line.frustumCulled = false;
  scene.add(line);
  return line;
}
function setLine(line, pts) {
  const a = line.geometry.attributes.position;
  pts.forEach((p, i) => a.setXYZ(i, p.x, p.y, p.z));
  a.needsUpdate = true;
  line.geometry.setDrawRange(0, pts.length);
}
// 帯（テスラの青い帯に当たる）：細い円柱をつないで太く見せる
function makeBand(color, opacity, onTop = true) {
  const g = new THREE.Group();
  g.userData.mat = new THREE.MeshBasicMaterial({ color, transparent: true, opacity, depthWrite: false, depthTest: !onTop });
  g.renderOrder = 10;
  scene.add(g);
  return g;
}
const cyl = new THREE.CylinderGeometry(1, 1, 1, 8, 1, true);
const sph = new THREE.SphereGeometry(1, 10, 8);
function setBand(g, pts, r, keep = false) {
  if (!keep) while (g.children.length) g.remove(g.children[0]);
  for (let i = 0; i < pts.length; i++) {
    const s = new THREE.Mesh(sph, g.userData.mat);
    s.renderOrder = 10;
    s.scale.setScalar(r);
    s.position.copy(pts[i]);
    g.add(s);
    if (i === 0) continue;
    const a = pts[i - 1], b = pts[i];
    const len = a.distanceTo(b);
    if (len < 1e-5) continue;
    const c = new THREE.Mesh(cyl, g.userData.mat);
    c.renderOrder = 10;
    c.scale.set(r, len, r);
    c.position.copy(a).add(b).multiplyScalar(0.5);
    c.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), b.clone().sub(a).normalize());
    g.add(c);
  }
}
const pathBand = makeBand(0x1668e3, 1);      // これから1秒で爪先が進む道
const jumpBand = makeBand(0xd93a3a, 1);         // 答えが切り替わって道が跳ぶ所
const endDot = new THREE.Mesh(sph, new THREE.MeshBasicMaterial({ color: 0x1668e3, depthTest: false }));
endDot.renderOrder = 11;
scene.add(endDot);

const TG = { ghost: true, ideal: false };
const idealLine = makeLine(0x8d9199, 1);
let MODE = 'path'; // path＝これから1秒の道 / jump＝答えの跳びの場所 / none＝線を出さない
// 跳びの場所を見せるもの：この回で爪先が通った道（灰）と、カクッとなった所を赤く
const wholePath = makeLine(0xc2c2c2, 1); // この回の道ぜんぶ（薄い灰）
const pastPath = makeLine(0x444444, 1);  // いままでに通った所（濃い灰）
const nowDot = new THREE.Mesh(new THREE.SphereGeometry(1, 16, 12), new THREE.MeshBasicMaterial({ color: 0x1668e3, depthTest: false }));
nowDot.renderOrder = 13;
nowDot.scale.setScalar(0.0055);
scene.add(nowDot);
const jumpDots = makeBand(0xd93a3a, 1);
const JUMP_LABEL = 10; // これより大きい跳びには数字の札を付ける
let jumpLabels = [];
function buildJumpView() {
  const pts = cur.tipState;
  const g = wholePath.geometry;
  g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(pts.flatMap((p) => [p.x, p.y, p.z])), 3));
  g.setDrawRange(0, pts.length);
  while (jumpDots.children.length) jumpDots.remove(jumpDots.children[0]);
  jumpLabels.forEach((l) => l.el.remove());
  jumpLabels = [];
  for (const [c, ch] of Object.entries(cur.chunks)) {
    const d = cur.t.jumps?.[c - 1];
    if (!(d > JUMP_RED)) continue;
    // 切り替えの前後 0.1 秒の道を赤くする（ここで動きがカクッとなった）
    const seg = pts.slice(Math.max(0, ch.s - 3), Math.min(pts.length, ch.s + 4));
    setBand(jumpDots, seg, 0.0026, true);
    if (d > JUMP_LABEL) {
      const el = document.createElement('div');
      el.className = 'jlbl';
      el.textContent = `${Math.round(d)}°`;
      $('stage').appendChild(el);
      jumpLabels.push({ el, p: pts[ch.s], d });
    }
  }
  const nBig = Object.keys(cur.chunks).filter((c) => cur.t.jumps?.[c - 1] > JUMP_RED).length;
  $('jumpCount').textContent = nBig ? `この回は ${nBig} か所` : 'この回は、カクッとなる所はありませんでした（ずれはどれも3°以下）';
}
let cur, F = 0, playing = false, speed = 1, lastT = 0;

function prepare(key) {
  const t = trials[key];
  const gripM = [];
  const tipState = t.state.map((q) => { const p = tipOf(calc, q); gripM.push(calc.grip.matrixWorld.clone()); return p; });
  const tipAct = t.action.map((q) => tipOf(calc, q));
  const grip = t.state.map((q) => q[5]);
  // つかんでいる間＝爪の値がブロックをはさんだ値（約7〜16）にとどまっている所。いちばん長く続いた所をつかんだ区間とする
  // （何もはさまずに閉じ切ると値は約1、開くと20より大きい）
  let close = -1, release = -1, best = 0;
  for (let i = 0; i < grip.length; ) {
    if (grip[i] > 7 && grip[i] < 16) {
      let j = i;
      while (j + 1 < grip.length && grip[j + 1] > 6 && grip[j + 1] < 17) j++;
      if (j - i + 1 > best) { best = j - i + 1; close = i; release = j + 1 < grip.length ? j + 1 : -1; }
      i = j + 1;
    } else i++;
  }
  if (best < 20) { close = -1; release = -1; }
  // 爪の向き：動く爪の回る軸と、爪先へ向かう向きから「爪が閉じる向き」を出す
  const jawAxis = rb.joints.find((j) => j.name === 'gripper');
  const jawFrame = new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(...jawAxis.rpy, 'ZYX'));
  function graspInfo(f) {
    const G = gripM[f], tip = tipState[f];
    const base = new THREE.Vector3().setFromMatrixPosition(G);
    const approach = tip.clone().sub(base).normalize();
    const R = new THREE.Matrix4().extractRotation(G).multiply(jawFrame);
    const axis = new THREE.Vector3(...jawAxis.axis).applyMatrix4(R).normalize();
    const closeDir = new THREE.Vector3().crossVectors(axis, approach).normalize();
    // ブロックの真ん中：爪先から付け根側へ11mm入った高さで、動かない爪の内側の面（爪先の点から-2.6mm）に
    // ブロックの面が当たる所。爪先の点（gripper_frame_link）は動かない爪の先にあり、爪の間の真ん中ではない
    const center = tip.clone().addScaledVector(approach, -0.011).addScaledVector(closeDir, -0.0036 + BS / 2); // 1mm のすき間
    return { center, yaw: Math.atan2(closeDir.y, closeDir.x) };
  }
  const b = place.blocks[key] || PLACES[t.place];
  let blockPos = b ? new THREE.Vector3(b[0], b[1], BS / 2) : tipState[Math.max(close, 0)].clone().setZ(BS / 2);
  let blockYaw = BOX_TURN;
  const carried = close >= 0; // はさんだ区間があれば運ぶ（失敗の回でも、途中で落とした所まで）
  if (close >= 0) {
    const gi = graspInfo(close);
    const near = Math.hypot(gi.center.x - blockPos.x, gi.center.y - blockPos.y) < 0.035;
    // つかめた回：ブロックは爪が閉じた所にあったとみなす（カメラからの位置は1cm前後ずれるため、爪の間にそろえる）
    if (carried) blockPos = new THREE.Vector3(gi.center.x, gi.center.y, BS / 2);
    // 向きは、ブロックの面が爪の面と平行になるようにそろえる
    if (carried || near) blockYaw = gi.yaw;
  }
  const blockQ = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), blockYaw);
  // かたまりごとの範囲
  const chunks = {};
  t.chunk_id.forEach((c, i) => { (chunks[c] ||= { s: i, e: i }).e = i; });

  // ブロックの動きを先に全コマ計算しておく（物理は回さない簡単な決まり）
  // 1) 机の上にあるとき：爪の形（頂点）がブロックに入ったら、爪が閉じる向きに押し出す。両側から当たれば、はさまれて真ん中に寄る
  // 2) はさんでいる間：爪と一緒に動く   3) 離したら真下に落ちて、机か箱の底に止まる
  // 爪がブロックに入っていたら、いちばん少ない動きで外へ押し出す（前後左右の4方向から選ぶ）。
  // 両側の爪から逆向きに押されたら、はさまれたとみなして真ん中に寄せ、向きを爪にそろえる
  let squeezed = false;
  function pushOut(f, p, yaw, grasping = false) {
    const tip = tipState[f];
    if (Math.hypot(tip.x - p.x, tip.y - p.y) > 0.07 || tip.z > 0.08) return yaw;
    const gi = graspInfo(f);
    const qf = t.state[f];
    setPose(calc, grasping && qf[5] < 12 ? [...qf.slice(0, 5), 12] : qf);
    calc.root.updateMatrixWorld(true);
    for (let it = 0; it < 4; it++) {
      const by = grasping ? gi.yaw : yaw;
      const u = new THREE.Vector3(Math.cos(by), Math.sin(by), 0), w = new THREE.Vector3(-u.y, u.x, 0);
      const dirs = [u, u.clone().negate(), w, w.clone().negate()];
      const moves = [];
      for (const [mesh] of jawMeshes(calc)) {
        const need = [0, 0, 0, 0];
        let hit = false;
        const pos = mesh.geometry.attributes.position;
        for (let i = 0; i < pos.count; i += 2) {
          vtx.fromBufferAttribute(pos, i).applyMatrix4(mesh.matrixWorld).sub(p);
          if (vtx.z < -BS / 2 || vtx.z > BS / 2) continue;
          const a = vtx.dot(u), c = vtx.dot(w);
          if (Math.abs(a) >= BS / 2 || Math.abs(c) >= BS / 2) continue;
          hit = true;
          dirs.forEach((d, k) => { need[k] = Math.max(need[k], vtx.dot(d) + BS / 2); });
        }
        if (!hit) continue;
        moves.push(need);
      }
      if (!moves.length) break;
      yaw = gi.yaw;
      const best = (need) => { const k = need.indexOf(Math.min(...need)); return dirs[k].clone().multiplyScalar(need[k]); };
      if (moves.length === 1) { p.add(best(moves[0])); continue; }
      const m0 = best(moves[0]), m1 = best(moves[1]);
      if (grasping && m0.dot(m1) < 0) { p.add(m0.add(m1).multiplyScalar(0.5)); squeezed = true; continue; }
      // 両方の爪に当たっていて、はさめない（爪が閉じ切っている）ときは、両方から外れる向きに押し出す
      p.add(best(moves[0].map((x, k) => Math.max(x, moves[1][k]))));
    }
    return yaw;
  }
  const bp = [], bq = [], sq = []; // sq＝ブロックが爪の間にはさまっているコマ
  const zAxis = new THREE.Vector3(0, 0, 1);
  const vtx = new THREE.Vector3();
  let p = blockPos.clone(), yaw = blockYaw, hold = null, dropFrom = null, landed = false;
  for (let f = 0; f < t.state.length; f++) {
    const holding = carried && f >= close && (release < 0 || f < release);
    if (holding) {
      if (!hold) {
        // つかんだコマ：ブロックを爪の間に置き直し、両側の爪にはさまれる位置まで押し合わせてから、爪にくっつける
        const gi = graspInfo(f);
        p.set(gi.center.x, gi.center.y, groundAt(gi.center.x, gi.center.y) + BS / 2);
        yaw = gi.yaw;
        yaw = pushOut(f, p, yaw, true);
        p.z = groundAt(p.x, p.y) + BS / 2;
      }
      if (!hold) hold = gripM[f].clone().invert().multiply(new THREE.Matrix4().compose(p, new THREE.Quaternion().setFromAxisAngle(zAxis, yaw), new THREE.Vector3(1, 1, 1)));
      new THREE.Matrix4().multiplyMatrices(gripM[f], hold).decompose(_p, _q, _s);
      { const [lx, ly] = boxLocal(_p.x, _p.y); const inBox = Math.abs(lx) < BW / 2 && Math.abs(ly) < BW / 2; _p.z = Math.max(_p.z, (inBox ? FLOOR : 0) + BS / 2); } // 運ぶ間は爪にくっついたまま（壁の高さで持ち上げない）
      bp.push(_p.clone()); bq.push(_q.clone()); sq.push(true);
      dropFrom = { p: _p.clone(), q: _q.clone(), f };
      continue;
    }
    if (dropFrom) {
      if (!dropFrom.settled) { const sp = settleInBox(dropFrom.p); dropFrom.p.x = sp.x; dropFrom.p.y = sp.y; dropFrom.settled = true; }
      // 離したあと：真下へ落とす
      if (groundAt(dropFrom.p.x, dropFrom.p.y) !== FLOOR) { const tz = dropFrom.p.z; pushOut(f, dropFrom.p, 0); dropFrom.p.z = tz; } // 箱の外に落ちるときは、開く爪からも押し出す
      const g = groundAt(dropFrom.p.x, dropFrom.p.y) + BS / 2;
      const ts = (f - dropFrom.f) / 30;
      const z = Math.max(g, dropFrom.p.z - 0.5 * 9.8 * ts * ts);
      const q = dropFrom.q.clone();
      if (z <= g) { yaw = new THREE.Euler().setFromQuaternion(q, 'ZYX').z; q.setFromAxisAngle(zAxis, yaw); p = new THREE.Vector3(dropFrom.p.x, dropFrom.p.y, g); if (f > release + 15) { dropFrom = null; landed = groundAt(p.x, p.y) === FLOOR; } }
      bp.push(new THREE.Vector3(dropFrom ? dropFrom.p.x : p.x, dropFrom ? dropFrom.p.y : p.y, z)); bq.push(q); sq.push(false);
      continue;
    }
    // 机の上：爪が近いときだけ当たりを調べる
    p.z = groundAt(p.x, p.y) + BS / 2;
    squeezed = false;
    if (!landed) yaw = pushOut(f, p, yaw); // 箱に入ったあとは、戻る爪で押し出さない（机に落ちたときは押す）
    bp.push(p.clone()); bq.push(new THREE.Quaternion().setFromAxisAngle(zAxis, yaw)); sq.push(squeezed);
  }
  // 記録の爪先が机の面より下に来たコマ（実物は机に当たって止まっている所。数ミリは校正のずれ）
  const touch = tipState.map((p) => p.z < 0.001);
  const ip = ideal[t.place];
  const idealTips = ip ? ip.path.map((q) => tipOf(calc, q)) : [];
  return { key, t, tipState, tipAct, close, release, chunks, carried, gripM, touch, ip, idealTips, bp, bq, sq, };
}

function jumpColor(d) { return d != null && d > JUMP_RED ? '#d93a3a' : '#b9b9b9'; }

function drawTimeline() {
  const cv = $('tl'), ctx = cv.getContext('2d');
  const W = (cv.width = cv.clientWidth * devicePixelRatio), H = (cv.height = cv.clientHeight * devicePixelRatio);
  ctx.clearRect(0, 0, W, H);
  const n = cur.t.state.length;
  const ids = Object.keys(cur.chunks).map(Number).sort((a, b) => a - b);
  for (const c of ids) {
    if (c === 0) continue;
    const d = cur.t.jumps?.[c - 1];
    const x = (cur.chunks[c].s / n) * W;
    const h = d == null ? H * 0.3 : Math.min(1, 0.25 + d / 40) * H;
    ctx.fillStyle = jumpColor(d);
    ctx.fillRect(x - devicePixelRatio, H - h, 2 * devicePixelRatio, h);
  }
  ctx.fillStyle = '#1668e3';
  ctx.fillRect((F / n) * W - devicePixelRatio, 0, 2 * devicePixelRatio, H);
}

const _p = new THREE.Vector3(), _q = new THREE.Quaternion(), _s = new THREE.Vector3();
// ブロックの底が机・箱の底より下に行かないようにする高さ
// 箱の座標（箱の真ん中から、箱の向きにそろえた x・y）
function boxLocal(x, y) {
  const dx = x - place.box[0], dy = y - place.box[1];
  const c = Math.cos(-BOX_TURN), sn = Math.sin(-BOX_TURN);
  return [c * dx - sn * dy, sn * dx + c * dy];
}
// ブロックの底が来てよいいちばん低い高さ：箱の中は箱の底、箱の壁の上は壁の高さ、それ以外は机
function groundAt(x, y) {
  const [lx, ly] = boxLocal(x, y);
  const inner = BW / 2 - T - BS / 2, outer = BW / 2 + BS / 2;
  if (Math.abs(lx) < inner && Math.abs(ly) < inner) return FLOOR;
  if (Math.abs(lx) < outer && Math.abs(ly) < outer) return BH;
  return 0;
}
// 箱の壁にかかって落ちたブロックは、箱の中へすべり込ませる（壁の上には止めない）
function settleInBox(p) {
  const [lx, ly] = boxLocal(p.x, p.y);
  const inner = BW / 2 - T - BS / 2, outer = BW / 2 + BS / 2;
  if (!(Math.abs(lx) < outer && Math.abs(ly) < outer)) return p;
  const cx = Math.max(-inner, Math.min(inner, lx)), cy = Math.max(-inner, Math.min(inner, ly));
  const c = Math.cos(BOX_TURN), sn = Math.sin(BOX_TURN);
  return new THREE.Vector3(place.box[0] + c * cx - sn * cy, place.box[1] + sn * cx + c * cy, p.z);
}
function placeBlock(f) {
  block.position.copy(cur.bp[f]);
  block.quaternion.copy(cur.bq[f]);
}
// 爪の形（動かない爪＝-1 の側、動く爪＝+1 の側）
function jawMeshes(robot) {
  if (!robot._jaws) {
    robot._jaws = [];
    robot.root.traverse((m) => {
      if (m.isMesh && m.name === 'wrist_roll_follower_so101_v1') robot._jaws.push([m, -1]);
      if (m.isMesh && m.name === 'moving_jaw_so101_v1') robot._jaws.push([m, 1]);
    });
  }
  return robot._jaws;
}
function update() {
  const t = cur.t, n = t.state.length;
  F = Math.max(0, Math.min(n - 1, F));
  const f = Math.floor(F);
  // ブロックをはさんでいるコマは、爪の開きをブロックの幅（2.4cm）より狭く描かない
  // （爪の値と開きの対応は1台ごとに少しずれるため、そのまま描くと爪がブロックに入って見える）
  const q0 = t.state[f];
  setPose(arm, cur.sq[f] && q0[5] < 12 ? [...q0.slice(0, 5), 12] : q0);

  // これから1秒で爪先が進む道（実際に送った指令を、爪先の位置に直したもの）
  const cid = t.chunk_id[f];
  const ch = cur.chunks[cid];
  const end = Math.min(n - 1, f + AHEAD);
  const path = cur.tipAct.slice(f, end + 1);
  const showPath = MODE === 'path';
  setBand(pathBand, showPath && path.length > 1 ? path : [], 0.0022);
  endDot.visible = showPath && path.length > 1;
  if (endDot.visible) { endDot.position.copy(path[path.length - 1]); endDot.scale.setScalar(0.0045); }
  while (jumpBand.children.length) jumpBand.remove(jumpBand.children[0]);
  setPose(ghost, t.action[end]);
  ghost.root.visible = TG.ghost; // 線の切り替えとは別に、ボタンだけで出し入れする
  // 理想の動きを重ねる（同じ場所の理想の道を、同じ経過時間で動かす）
  const showIdeal = TG.ideal && cur.ip && !t.ideal;
  idealArm.root.visible = idealLine.visible = !!showIdeal;
  if (showIdeal) {
    setPose(idealArm, cur.ip.path[Math.min(f, cur.ip.path.length - 1)]);
    setLine(idealLine, cur.idealTips);
  }
  wholePath.visible = jumpDots.visible = pastPath.visible = nowDot.visible = MODE === 'jump';
  if (MODE === 'jump') {
    const g2 = pastPath.geometry;
    g2.setAttribute('position', new THREE.BufferAttribute(new Float32Array(cur.tipState.slice(0, f + 1).flatMap((p) => [p.x, p.y, p.z])), 3));
    g2.setDrawRange(0, f + 1);
    nowDot.position.copy(cur.tipState[f]);
  }

  // ブロック
  placeBlock(f);

  // 追いかけの視点
  if (camMode === 'chase') {
    const tp = cur.tipState[f];
    controls.target.lerp(tp, 0.15);
    const dir = new THREE.Vector3(tp.x, tp.y, 0);
    if (dir.length() < 0.05) dir.set(1, 0, 0);
    dir.normalize();
    const side = new THREE.Vector3(-dir.y, dir.x, 0);
    const want = tp.clone().addScaledVector(dir, -0.22).addScaledVector(side, -0.16);
    want.z = tp.z + 0.42;
    camera.position.lerp(want, 0.12);
  }

  // 数字
  const d = t.jumps?.[cid];
  $('time').textContent = (f / 30).toFixed(1);
  $('chunk').textContent = cid + 1;
  $('left').textContent = ((ch.e - f + 1) / 30).toFixed(1);
  const nj = $('nextjump');
  nj.textContent = d == null ? '-' : d.toFixed(1);
  nj.classList.toggle('hit', d != null && d > JUMP_RED);

  // 動画
  const v = $('vid');
  if (!playing && Math.abs(v.currentTime - f / 30) > 0.05) v.currentTime = f / 30;
  drawTimeline();
}

let camMode = 'free';
function setCam(mode) {
  camMode = mode;
  camera.up.set(...(mode === 'top' ? [1, 0, 0] : [0, 0, 1]));
  document.querySelectorAll('[data-cam]').forEach((b) => b.classList.toggle('on', b.dataset.cam === mode));
  if (mode === 'top') { controls.target.set(0.2, 0, 0); camera.position.set(0.2, 0.0001, 1.05); }
  if (mode === 'side') { controls.target.set(0.2, 0, 0.08); camera.position.set(0.2, -0.95, 0.16); }
  if (mode === 'free') { controls.target.set(0.18, 0, 0.08); camera.position.set(0.95, 0.22, 0.42); }
  controls.update();
}
controls.addEventListener('start', () => { if (camMode === 'chase') setCam('free'); });

function loadTrial(key) {
  cur = prepare(key);
  F = 0;
  const t = cur.t;
  const v = $('vid');
  document.querySelectorAll('.aiOnly').forEach((e) => (e.hidden = !!t.ideal));
  $('pathSrc').textContent = t.ideal ? '理想の道の指令' : 'AI の指令';
  // サイトに置いたときは、録画は R2（/media/）から読む。試作の artifact では同じフォルダから読む
  const VID = location.pathname.startsWith('/sim/') ? `/media/rv_so101_${key}_v1.mp4` : key + '.mp4';
  fetch(VID).then((r) => r.blob()).then((b) => {
    if (cur.key !== key) return;
    if (v.dataset.url) URL.revokeObjectURL(v.dataset.url);
    v.dataset.url = URL.createObjectURL(b);
    v.src = v.dataset.url;
    v.addEventListener('loadeddata', () => { v.currentTime = Math.floor(F) / 30; }, { once: true });
  });
  $('meta').innerHTML = t.ideal
    ? `<b>理想の動き</b>・場所${t.place}・${(t.state.length / 30).toFixed(1)}秒（お手本から作った理想の道を、実機に流して録った回）`
    : `<b>${t.model}</b>・場所${t.place}・${t.result === 'success' ? '成功' : t.result === 'failure' ? '<span class="ng">失敗</span>' : t.result}・${(t.state.length / 30).toFixed(1)}秒・答え ${Object.keys(cur.chunks).length} 回`;
  curPlace = t.place;
  renderList();
  document.querySelectorAll('.sc').forEach((b) => b.classList.toggle('on', b.dataset.k === key));
  $('seek').max = t.state.length - 1;
  buildJumpView();
  update();
}

const RES = { success: '成功', failure: '失敗' };
let curPlace = 4;
function renderList() {
  document.querySelectorAll('[data-place]').forEach((b) => b.classList.toggle('on', +b.dataset.place === curPlace));
  const list = Object.entries(trials).filter(([, t]) => t.place === curPlace).sort(([a, ta], [b, tb]) => (tb.ideal ? 1 : 0) - (ta.ideal ? 1 : 0) || a.localeCompare(b));
  $('trials').innerHTML = list.map(([k, t]) => {
    if (t.ideal) return `<button class="sc" data-k="${k}"><b>理想の動き</b><span>理想の道を実機に流した回・${(t.state.length / 30).toFixed(1)}秒</span></button>`;
    const ts = k.slice(6);
    const when = `${ts.slice(4, 6)}/${ts.slice(6, 8)} ${ts.slice(9, 11)}:${ts.slice(11, 13)}`;
    return `<button class="sc" data-k="${k}"><b>${t.model}・${RES[t.result] || t.result}</b><span>${when} の実機・${(t.state.length / 30).toFixed(1)}秒</span></button>`;
  }).join('');
  document.querySelectorAll('.sc').forEach((b) => {
    b.classList.toggle('on', cur && b.dataset.k === cur.key);
    b.onclick = () => { if (playing) $('playBtn').click(); loadTrial(b.dataset.k); };
  });
}
document.querySelectorAll('[data-place]').forEach((b) => (b.onclick = () => { curPlace = +b.dataset.place; renderList(); }));
$('playBtn').onclick = () => {
  playing = !playing;
  $('playBtn').textContent = playing ? '一時停止' : '再生';
  const v = $('vid');
  if (playing) { if (F >= cur.t.state.length - 1) F = 0; v.currentTime = F / 30; v.playbackRate = speed; v.play(); } else v.pause();
};
$('seek').oninput = (e) => { F = +e.target.value; update(); };
document.querySelectorAll('[data-spd]').forEach((b) => (b.onclick = () => {
  speed = +b.dataset.spd;
  $('vid').playbackRate = speed;
  document.querySelectorAll('[data-spd]').forEach((x) => x.classList.toggle('on', x === b));
}));
document.querySelectorAll('[data-cam]').forEach((b) => (b.onclick = () => setCam(b.dataset.cam)));
document.querySelectorAll('[data-mode]').forEach((b) => (b.onclick = () => {
  MODE = b.dataset.mode;
  document.querySelectorAll('[data-mode]').forEach((x) => x.classList.toggle('on', x === b));
  document.querySelectorAll('[data-for]').forEach((x) => (x.hidden = x.dataset.for !== MODE));
  update();
}));
document.querySelectorAll('[data-tg]').forEach((b) => (b.onclick = () => {
  TG[b.dataset.tg] = !TG[b.dataset.tg];
  b.classList.toggle('on', TG[b.dataset.tg]);
  update();
}));
$('tl').onclick = (e) => {
  const r = e.target.getBoundingClientRect();
  F = ((e.clientX - r.left) / r.width) * cur.t.state.length;
  if (playing) $('vid').currentTime = F / 30;
  update();
};
$('prevsw').onclick = () => jumpTo(-1);
$('nextsw').onclick = () => jumpTo(1);
function jumpTo(dir) {
  const f = Math.floor(F), cid = cur.t.chunk_id[f];
  const target = cur.chunks[cid + (dir > 0 ? 1 : 0)];
  let s = target ? target.s : f;
  if (dir < 0) s = cur.chunks[Math.max(0, cid - (f === cur.chunks[cid].s ? 1 : 0))].s - 8;
  else s -= 8; // 切り替えの少し前で止める
  F = Math.max(0, s);
  if (playing) $('playBtn').click();
  update();
}
let spaceDown = false, spaceUsed = false;
controls.addEventListener('start', () => { if (spaceDown) spaceUsed = true; });
window.addEventListener('keyup', (e) => {
  if (e.key !== ' ') return;
  e.preventDefault();
  spaceDown = false;
  controls.mouseButtons.LEFT = THREE.MOUSE.ROTATE;
  renderer.domElement.style.cursor = '';
  if (!spaceUsed) $('playBtn').click();
});
window.addEventListener('keydown', (e) => {
  if (e.key === ' ') {
    // スペースを押している間はドラッグで視点を平行に動かす。ドラッグせずに離したら再生と一時停止
    e.preventDefault();
    if (!e.repeat) { spaceDown = true; spaceUsed = false; controls.mouseButtons.LEFT = THREE.MOUSE.PAN; renderer.domElement.style.cursor = 'move'; }
  }
  if (e.key === 'ArrowRight') { F += e.shiftKey ? 15 : 1; update(); }
  if (e.key === 'ArrowLeft') { F -= e.shiftKey ? 15 : 1; update(); }
});

function resize() {
  const w = view.clientWidth, h = view.clientHeight;
  renderer.setSize(w, h);
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(view);
resize();

function loop(now) {
  if (playing) {
    const v = $('vid');
    if (!v.paused && v.readyState >= 2) F = v.currentTime * 30;
    else F += ((now - lastT) / 1000) * 30 * speed;
    if (F >= cur.t.state.length - 1) { F = cur.t.state.length - 1; $('playBtn').click(); }
    $('seek').value = Math.floor(F);
    update();
  } else if (camMode === 'chase') update();
  lastT = now;
  controls.update();
  renderer.render(scene, camera);
  // 跳びの数字の札
  // 大きい跳びから置き、近くに札があるときは小さいほうを出さない（重なり防ぎ）
  const placed = [];
  for (const l of [...jumpLabels].sort((a, b) => b.d - a.d)) {
    if (MODE !== 'jump') { l.el.style.display = 'none'; continue; }
    const v = l.p.clone().project(camera);
    const x = ((v.x + 1) / 2) * view.clientWidth, y = ((1 - v.y) / 2) * view.clientHeight - 8;
    const near = placed.some(([px, py]) => Math.abs(px - x) < 34 && Math.abs(py - y) < 18);
    l.el.style.display = near ? 'none' : 'block';
    if (near) continue;
    placed.push([x, y]);
    l.el.style.left = x + 'px';
    l.el.style.top = y + 'px';
  }
  // 場所の番号の札
  for (const pm of placeMarks) {
    const v = pm.pos.clone().project(camera);
    pm.el.style.left = ((v.x + 1) / 2) * view.clientWidth + 'px';
    pm.el.style.top = ((1 - v.y) / 2) * view.clientHeight + 20 + 'px'; // 印の少し手前に置き、ブロックと重ねない
    pm.el.classList.toggle('on', pm.p === cur.t.place);
  }
  // 「いま」の札
  const nl = $('nowLabel');
  if (nowDot.visible) {
    const v = nowDot.position.clone().project(camera);
    nl.style.display = 'block';
    nl.style.left = ((v.x + 1) / 2) * view.clientWidth + 'px';
    nl.style.top = ((1 - v.y) / 2) * view.clientHeight - 10 + 'px';
  } else nl.style.display = 'none';
  // 道の終わりに「1秒後」の札を付ける
  const lb = $('endLabel');
  if (endDot.visible) {
    const v = endDot.position.clone().project(camera);
    lb.style.display = 'block';
    lb.style.left = ((v.x + 1) / 2) * view.clientWidth + 'px';
    lb.style.top = ((1 - v.y) / 2) * view.clientHeight - 12 + 'px';
  } else lb.style.display = 'none';
  requestAnimationFrame(loop);
}
loadTrial('so101_20261127_073800');
setCam('free');
requestAnimationFrame(loop);
