// AcademyWorld.jsx — 學院的 3D 世界
//
// 一條往下、往遠處延伸的路線，沿路是一座座平台，每座平台放一個「展品」
// （一顆輪子、一個底盤、一整台車…）。上課不是換頁，而是鏡頭在展品周圍換視角。
//
// 這個檔案只管 3D：平台、路線、展品、鏡頭、標籤。課程內容在 Academy.jsx。
//
// 展品（exhibit）介面：
//   group            THREE.Group，原點在平台表面中心
//   shots            { 名稱: { pos:[x,y,z], look:[x,y,z] } }，座標相對平台中心
//   apply(shot, params, reveal) → 設定這個視角要顯示什麼，回傳標籤 [{ at:[x,y,z], text, tone }]
//
// 座標：+x 右、+y 上、路線往 -z 走。展品的車頭朝 -z。

// 平台位置：左右交錯、一路往下。r＝平台半徑。
const ACADEMY_PLACES = [
  { id: "start",      pos: [0, 0, 0],        r: 2.6, exhibit: "start" },
  { id: "wheel",      pos: [7, -1.6, -17],   r: 5,   exhibit: "wheel" },
  { id: "chassis",    pos: [-7, -3.2, -34],  r: 5.6, exhibit: "chassis" },
  { id: "steering",   pos: [7, -4.8, -51],   r: 5.6, exhibit: "steering" },
  { id: "suspension", pos: [-7, -6.4, -67],  r: 5,   exhibit: "suspension" },
  { id: "brake",      pos: [7, -8, -83],     r: 5.6, exhibit: "drivetrain" },
  { id: "car",        pos: [-2, -10.5, -106], r: 8,  exhibit: "car" },
  { id: "rules",      pos: [8, -13, -130],   r: 4.4, exhibit: "ghost" },
];

function academyCssColor(name, fallback) {
  const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
  return v || fallback;
}

async function createAcademyWorld({ canvas, labelLayer, onPickPlace }) {
  const THREE = await import("three");
  const { RoomEnvironment } = await import("three/addons/environments/RoomEnvironment.js");
  const V = (a) => new THREE.Vector3(a[0], a[1], a[2]);
  const UP = new THREE.Vector3(0, 1, 0);
  const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;

  const scene = new THREE.Scene();
  const pmrem = new THREE.PMREMGenerator(renderer);
  const envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
  scene.environment = envTex;
  scene.environmentIntensity = 0.55;
  pmrem.dispose();
  scene.fog = new THREE.Fog(0xffffff, 26, 120);

  const hemi = new THREE.HemisphereLight(0xffffff, 0x888899, 0.9);
  scene.add(hemi);
  const sun = new THREE.DirectionalLight(0xffffff, 2.1);
  sun.castShadow = true;
  sun.shadow.mapSize.set(2048, 2048);
  sun.shadow.radius = 6;
  sun.shadow.bias = -0.0004;
  Object.assign(sun.shadow.camera, { left: -11, right: 11, top: 11, bottom: -11, near: 1, far: 60 });
  scene.add(sun, sun.target);

  const camera = new THREE.PerspectiveCamera(32, 16 / 9, 0.1, 600);

  // ── 材質（顏色跟著網站的淺色／深色主題） ──
  const mat = {
    platform: new THREE.MeshStandardMaterial({ roughness: 0.95, metalness: 0 }),
    clay:     new THREE.MeshStandardMaterial({ roughness: 0.7, metalness: 0.05 }),
    tire:     new THREE.MeshStandardMaterial({ roughness: 0.92, metalness: 0, transparent: true, side: THREE.DoubleSide }),
    route:    new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.9 }),
    accent:   new THREE.MeshStandardMaterial({ roughness: 0.5, metalness: 0 }),
    blue:     new THREE.MeshStandardMaterial({ roughness: 0.5, metalness: 0 }),
    soft:     new THREE.MeshStandardMaterial({ roughness: 0.6, metalness: 0 }),
    ghost:    new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.35 }),
    ink:      new THREE.MeshBasicMaterial(),   // 尺寸線：跟文字同色
  };
  function refreshTheme() {
    const dark = document.documentElement.getAttribute("data-appearance") === "dark";
    const bg = new THREE.Color(academyCssColor("--bg-primary", dark ? "#1B1B1F" : "#F2F2F7"));
    scene.fog.color.copy(bg);
    mat.platform.color.set(dark ? "#2C2C32" : "#FFFFFF");
    mat.clay.color.set(dark ? "#B4B6BE" : "#DCDDE3");
    mat.tire.color.set(dark ? "#4A4B52" : "#2B2C31");
    mat.route.color.set(dark ? "#6C6C74" : "#B9BAC2");
    mat.ghost.color.set(dark ? "#6C6C74" : "#B9BAC2");
    mat.soft.color.set(dark ? "#8D8E96" : "#8E8E96");
    mat.ink.color.set(dark ? "#D8D9DE" : "#3A3B40");
    mat.accent.color.set(academyCssColor("--orange", "#FF9500"));
    mat.accent.emissive.set(academyCssColor("--orange", "#FF9500")).multiplyScalar(0.25);
    mat.blue.color.set(academyCssColor("--blue", "#007AFF"));
    mat.blue.emissive.set(academyCssColor("--blue", "#007AFF")).multiplyScalar(0.25);
    hemi.intensity = dark ? 0.55 : 0.95;
    sun.intensity = dark ? 1.7 : 2.1;
  }
  refreshTheme();
  const themeWatch = new MutationObserver(refreshTheme);
  themeWatch.observe(document.documentElement, { attributes: true, attributeFilter: ["data-appearance"] });

  // ── 小工具 ──
  // 會「長出來／收回去」的物件：設 want＝0 或 1，每幀平滑縮放。
  const fx = [];
  function pop(obj) { obj.userData.want = 0; obj.userData.s = 0; obj.visible = false; fx.push(obj); return obj; }
  function show(obj, on) { obj.userData.want = on ? 1 : 0; }

  function tube(a, b, r, material) {
    const dir = b.clone().sub(a);
    const len = dir.length();
    const m = new THREE.Mesh(new THREE.CylinderGeometry(r, r, len, 14), material);
    m.position.copy(a).addScaledVector(dir, 0.5);
    m.quaternion.setFromUnitVectors(UP, dir.normalize());
    m.castShadow = true;
    return m;
  }

  // 箭頭：set(起點, 終點)
  function arrow(material, r = 0.075) {
    const g = new THREE.Group();
    const shaft = new THREE.Mesh(new THREE.CylinderGeometry(r, r, 1, 18), material);
    const head = new THREE.Mesh(new THREE.ConeGeometry(r * 2.8, r * 6.5, 24), material);
    shaft.castShadow = head.castShadow = true;
    g.add(shaft, head);
    g.set = (a, b) => {
      const dir = b.clone().sub(a);
      const len = Math.max(0.001, dir.length());
      const headLen = Math.min(r * 6.5, len * 0.6);
      g.position.copy(a);
      g.quaternion.setFromUnitVectors(UP, dir.normalize());
      shaft.scale.y = len - headLen;
      shaft.position.y = (len - headLen) / 2;
      head.scale.y = headLen / (r * 6.5);
      head.position.y = len - headLen / 2;
    };
    return pop(g);
  }

  // 一顆輪子：輪胎＋輪圈，輪軸沿 x，半徑 R，站在 y = 0 上。
  function makeWheel(R = 1.5) {
    const g = new THREE.Group();
    const k = R / 1.5;
    const profile = [
      [0.96, -0.5], [1.34, -0.5], [1.44, -0.46], [1.5, -0.36],
      [1.5, 0.36], [1.44, 0.46], [1.34, 0.5], [0.96, 0.5], [0.96, -0.5],
    ].map(([r, y]) => new THREE.Vector2(r * k, y * k));
    const tire = new THREE.Mesh(new THREE.LatheGeometry(profile, 72), mat.tire);
    tire.rotation.z = Math.PI / 2;
    tire.castShadow = true;

    const face = new THREE.Shape();
    face.absarc(0, 0, 0.95 * k, 0, Math.PI * 2, false);
    for (let i = 0; i < 5; i++) {
      const a = i / 5 * Math.PI * 2 + Math.PI / 2;
      const hole = new THREE.Path();
      hole.absarc(Math.cos(a) * 0.58 * k, Math.sin(a) * 0.58 * k, 0.2 * k, 0, Math.PI * 2, true);
      face.holes.push(hole);
    }
    const disc = new THREE.Mesh(
      new THREE.ExtrudeGeometry(face, { depth: 0.1 * k, bevelEnabled: false, curveSegments: 40 }), mat.clay);
    disc.rotation.y = Math.PI / 2;
    disc.position.x = 0.22 * k;
    const barrel = new THREE.Mesh(new THREE.CylinderGeometry(0.96 * k, 0.96 * k, 0.9 * k, 56, 1, true),
      new THREE.MeshStandardMaterial({ roughness: 0.7, metalness: 0.05, side: THREE.DoubleSide }));
    barrel.material.color = mat.clay.color;
    barrel.rotation.z = Math.PI / 2;
    const hub = new THREE.Mesh(new THREE.CylinderGeometry(0.2 * k, 0.2 * k, 0.5 * k, 28), mat.clay);
    hub.rotation.z = Math.PI / 2;
    hub.position.x = 0.2 * k;
    disc.castShadow = barrel.castShadow = true;
    g.add(tire, disc, barrel, hub);
    g.position.y = R;
    return g;
  }

  // ── 共用：鋼管空間桁架（L1 底盤和 L2 整車都用這一份） ──
  // t(a, b, r) 負責把一根管子加到對的群組。
  const P3 = (x, y, z) => new THREE.Vector3(x, y, z);
  function spaceFrame(t) {
    for (const s of [-1, 1]) {
      const bulkB = P3(s * 0.42, 0.28, -2.45), bulkT = P3(s * 0.42, 0.78, -2.45);
      const fhB = P3(s * 0.56, 0.28, -1.05), fhT = P3(s * 0.5, 1.05, -1.05);
      const mhB = P3(s * 0.62, 0.28, 0.25),  mhM = P3(s * 0.6, 1.02, 0.25), mhT = P3(s * 0.36, 1.75, 0.25);
      const rB = P3(s * 0.5, 0.28, 2.0),     rT = P3(s * 0.46, 0.82, 2.0);
      t(bulkB, bulkT); t(bulkB, fhB); t(fhB, mhB); t(mhB, rB); t(rB, rT);
      t(bulkT, fhT); t(fhB, fhT); t(fhT, mhM); t(mhB, mhM); t(mhM, mhT); t(mhM, rT); t(mhT, rT);
      t(bulkB, fhT, 0.035); t(fhB, mhM, 0.035); t(mhB, rT, 0.035);
      if (s === 1) for (const b of [bulkB, bulkT, fhB, fhT, mhB, mhT, rB, rT]) t(b, b.clone().setX(-b.x));
    }
  }
  // 上下 A 臂：從輪子內側接到車架
  function aArms(t, hx, zf, zr) {
    for (const s of [-1, 1]) {
      for (const [z, n1, n2] of [[zf, P3(s * 0.5, 0, -2.2), P3(s * 0.56, 0, -1.2)], [zr, P3(s * 0.6, 0, 0.9), P3(s * 0.5, 0, 1.95)]]) {
        for (const y of [0.3, 0.8]) {
          const hubPt = P3(s * (hx - 0.3), y === 0.3 ? 0.32 : 0.78, z);
          t(hubPt, n1.clone().setY(y), 0.028); t(hubPt, n2.clone().setY(y), 0.028);
        }
      }
    }
  }

  // ── 展品：一顆輪子 ──
  function wheelExhibit() {
    const group = new THREE.Group();
    const R = 1.5;
    const wheel = makeWheel(R);           // 輪軸沿 x：從 ±x 看是圓（側視），從 ±z 看是胎寬（正視）
    group.add(wheel);

    // 接地面：寬（x）≈ 胎面寬，長（z）比寬短。外層給 pop() 縮放，內層跟著胎寬變。
    const patch = pop(new THREE.Group());
    const patchIn = new THREE.Mesh(new THREE.CylinderGeometry(0.62, 0.62, 0.03, 40), mat.accent);
    patchIn.geometry.scale(0.75, 1, 0.55);
    patchIn.position.y = 0.02;
    patch.add(patchIn);
    group.add(patch);

    // 正視圖的胎寬尺寸線（量在輪胎頂上），內層跟著胎寬變
    const widthDim = pop(new THREE.Group());
    const widthDimIn = dimension(P3(-0.5, R * 2, 0), P3(0.5, R * 2, 0), P3(0, 1, 0), 0.45, { gap: 0.1 });
    widthDim.add(widthDimIn);
    group.add(widthDim);

    // tw＝胎寬倍數（「更寬的胎」那張變 1.6 倍），平滑追 twWant
    const st = { tw: 1, twWant: 1 };
    function setWidth() {
      wheel.scale.x = st.tw;
      widthDimIn.scale.x = st.tw;
      // 變寬，也變短一點（同樣的重量，胎壓可以放低）：面積仍然變大
      patchIn.scale.set(st.tw, 1, 1 - (st.tw - 1) * 0.25);
    }

    const a = { load: arrow(mat.blue), grip: arrow(mat.accent), drive: arrow(mat.accent), brake: arrow(mat.accent),
                left: arrow(mat.blue), right: arrow(mat.blue), weight: arrow(mat.blue), support: arrow(mat.soft) };
    Object.values(a).forEach(x => group.add(x));
    const side = -0.95;   // 箭頭畫在輪子左側（鏡頭這一邊），側面看不會被輪胎擋住

    return {
      group,
      shots: {
        // 路線在輪子的 −x 側。整課鏡頭只往一個方向繞：3D 左後上方 → 正側面（−x）→ 俯視 → 正視（從 +z 看）。
        // 輪軸沿 x，所以從 −x 看到的是輪子的圓（車頭 −z 在畫面左邊）；從 ±z 看到的是胎寬。
        // 俯視時鏡頭往 +z 偏一點：畫面上方＝車頭（−z），驅動朝上、煞車朝下、轉彎在左右。
        // 正視從 +z 看（單顆輪子前後對稱）：從俯視降下來不用轉 180°。
        hero:   { pos: [-10.2, 3.8, 5.6],  look: [0, 1.45, -0.4] },        // 3D：左後上方斜看
        patch:  { pos: [-9, 3.6, 0],       look: [0, 0.7, 0] },            // 側視（稍微抬高）：圓＋接地面的長
        side:   { pos: [-15.5, 2.8, -0.6], look: [0, 2.2, -0.6] },         // 正側視：力的箭頭都在畫面平面上
        sideUp: { pos: [0.6, 14, 0.5],     look: [0.6, 0.3, 0] },          // 俯視：驅動↑ 煞車↓ 轉彎←→
        front:  { pos: [-1.4, 3.6, 9.5],   look: [0, 1.1, 0] },            // 正視：胎寬＋接地面的寬
        wide:   { pos: [-11.5, 5.6, 8],    look: [0, 1.2, 0] },
      },
      apply(shot, p, reveal) {
        const is = (...names) => names.includes(shot.show);
        const labels = [];
        mat.tire.opacity = is("patch", "forces") ? 0.22 : is("width", "wide") ? 0.4 : 1;
        mat.tire.depthWrite = mat.tire.opacity > 0.5;
        show(patch, is("patch", "load", "forces", "width", "wide") || (is("draw") && reveal));
        show(widthDim, is("width", "wide"));
        st.twWant = is("wide") ? 1.6 : 1;
        if (is("width")) labels.push({ at: [0, R * 2 + 0.75, 0], text: "胎寬", tone: "dim" },
                                     { at: [0, 0.05, -0.8], text: "接地面的寬", tone: "accent" });
        if (is("wide")) labels.push({ at: [0, R * 2 + 0.75, 0], text: "更寬的胎", tone: "dim" },
                                    { at: [0, 0.05, -0.8], text: "更寬的接地面", tone: "accent" });

        const n = p.n ?? 750, mu = p.mu ?? 1, grip = n * mu;
        show(a.load, is("load"));
        show(a.grip, is("load"));
        if (is("load")) {
          const top = R * 2 + 0.35, len = n / 1500 * 2.4;
          a.load.set(new THREE.Vector3(side, top + len, 0), new THREE.Vector3(side, top, 0));
          a.grip.set(new THREE.Vector3(side, 0.12, 0), new THREE.Vector3(side, 0.12, -grip / 2250 * 4.2));
          labels.push({ at: [side, top + len + 0.35, 0], text: `垂直力 ${n} N`, tone: "blue" });
          labels.push({ at: [side, 0.55, -grip / 2250 * 4.2 - 0.2], text: `最大摩擦力 ${Math.round(grip)} N`, tone: "accent" });
        }

        show(a.drive, is("forces")); show(a.brake, is("forces"));
        show(a.left, is("forces"));  show(a.right, is("forces"));
        if (is("forces")) {
          const y = 0.1;
          a.drive.set(new THREE.Vector3(0, y, -0.75), new THREE.Vector3(0, y, -3.1));
          a.brake.set(new THREE.Vector3(0, y, 0.75),  new THREE.Vector3(0, y, 3.1));
          a.left.set(new THREE.Vector3(-0.85, y, 0),  new THREE.Vector3(-3.1, y, 0));
          a.right.set(new THREE.Vector3(0.85, y, 0),  new THREE.Vector3(3.1, y, 0));
          labels.push({ at: [0, y, -3.5], text: "驅動", tone: "accent" }, { at: [0, y, 3.5], text: "煞車", tone: "accent" },
                      { at: [-3.6, y, 0], text: "轉彎", tone: "blue" }, { at: [3.6, y, 0], text: "轉彎", tone: "blue" });
        }

        const ans = is("draw") && reveal;
        show(a.weight, ans); show(a.support, ans);
        if (ans) {
          a.weight.set(new THREE.Vector3(side, R, 0), new THREE.Vector3(side, 0.25, 0));
          a.support.set(new THREE.Vector3(side, 0.1, 1.9), new THREE.Vector3(side, 1.7, 1.9));
          show(a.grip, true);
          a.grip.set(new THREE.Vector3(side, 0.12, 0), new THREE.Vector3(side, 0.12, -2.4));
          labels.push({ at: [side, R + 0.3, 0], text: "重量", tone: "blue" },
                      { at: [side, 2.05, 1.9], text: "地面支撐力", tone: "soft" },
                      { at: [side, 0.55, -2.6], text: "摩擦力", tone: "accent" });
        }
        if (is("patch")) labels.push({ at: [-0.6, 0.05, 0.95], text: "接地面", tone: "accent" });
        return labels;
      },
      tick(dt) {
        if (st.tw === st.twWant) return;
        if (Math.abs(st.tw - st.twWant) < 0.002) st.tw = st.twWant;
        else st.tw += (st.twWant - st.tw) * (reduceMotion ? 1 : 1 - Math.pow(0.05, dt));
        setWidth();
      },
    };
  }

  // ── 共用：tools/envelope.html 設計的那台車（src/envelope-car.js） ──
  // 車架、轉向、懸吊三站都用它。參數讀設計工具存在這台裝置的值（同一個網址才讀得到），沒有就用預設值。
  // 單位：車子本身是 m，放進展品時整台放大 scale 倍。
  const { createCarKit } = await import(new URL("src/envelope-car.js", document.baseURI).href);
  const carMat = {
    clay: mat.clay, tire: mat.tire, frame: mat.clay, susp: mat.soft, man: mat.soft, helmet: mat.accent,
    seat: mat.soft, battery: mat.soft, motor: mat.soft, body: mat.ghost, floor: mat.ghost, wall: mat.ghost,
    rib: new THREE.LineBasicMaterial(),
  };
  const carSaved = (() => { try { return JSON.parse(localStorage.getItem("envelope-params-v18")) || {}; } catch { return {}; } })();
  function designCar({ scale = 2.7, driver = false, paint = null } = {}) {
    const kit = createCarKit(THREE, carMat);
    const holder = new THREE.Group();
    holder.scale.setScalar(scale);
    let car = null, key = null;
    // over：要蓋成什麼姿態（steer＝試轉內輪角°、bump＝試壓縮 mm）。一樣就不重蓋。
    function build(over = {}) {
      const k = JSON.stringify(over);
      if (k === key) return car;
      key = k;
      if (car) { holder.remove(car.group); car.group.traverse(o => o.geometry?.dispose()); }
      car = kit.buildCar({ ...carSaved, ...over }, { driver });
      car.group.traverse(o => {
        if (!o.isMesh) return;
        o.castShadow = true;
        const m2 = paint?.(o);
        if (m2) o.material = m2;
      });
      holder.add(car.group);
      return car;
    }
    build();
    // 車上的點（m）→ 展品座標
    const at = (v) => [v.x * holder.scale.x + holder.position.x, v.y * scale + holder.position.y, v.z * scale + holder.position.z];
    const part = (name) => { let f = null; car.group.traverse(o => { if (!f && o.userData.name === name) f = o; }); return f; };
    const ends = (name) => { const o = part(name); return o ? [at(o.userData.a), at(o.userData.b)] : null; };
    return { holder, build, at, part, ends, scale, get car() { return car; } };
  }
  const mix = (a, b, t = 0.5) => a.map((v, i) => v + (b[i] - v) * t);
  const add3 = (a, d) => a.map((v, i) => v + d[i]);

  // ── 展品：四個輪子加一個車架 ──
  // 車架（連同懸吊、轉向）從平台底下升上來，四個輪子一直都在原地。
  // 後面幾張示範「重量會跑」：加速時往後、轉彎時往外，四個輪子旁的柱子跟著變高變低。
  function chassisExhibit() {
    const group = new THREE.Group();
    const dc = designCar({ scale: 2.7 });
    group.add(dc.holder);
    const { m } = dc.car;
    const S = dc.scale, M = 300, H = 0.3;     // 示範用：整車 300 kg、重心高 300 mm
    const L = m.wb * S, T = m.tr * S;
    const zf = -L / 2, zr = L / 2, hx = T / 2;
    const corners = { fl: [-hx, zf], fr: [hx, zf], rl: [-hx, zr], rr: [hx, zr] };

    // 狀態：rise＝車架升起 0→1；ax／ay＝目前的縱向／側向 g（平滑追 want）
    const st = { rise: 0, riseWant: 0, ax: 0, axWant: 0, ay: 0, ayWant: 0, steer: 0, spin: false };
    function placeFrame() {
      const fr = dc.car.fr.group;
      const e = st.rise * st.rise * (3 - 2 * st.rise);
      fr.position.y = (e - 1) * 1.1;          // m：完全降下時整個埋在平台底下
      fr.visible = st.rise > 0.01;
      // 車身姿態：加速時車頭抬起、轉彎時往外側傾（放大約 3 倍才看得出來）
      fr.rotation.x = THREE.MathUtils.degToRad(3) * st.ax;
      fr.rotation.z = -THREE.MathUtils.degToRad(3) * st.ay;
    }
    placeFrame();

    // 尺寸線（工程圖畫法）：俯視圖量軸距、輪距；側視圖（公式那張）只量軸距，量在輪心高度
    const Rw = m.R * S, xo = hx + m.ww * S / 2;
    const dims = pop(new THREE.Group());
    const dWb = dimension(P3(xo, 0.03, zf), P3(xo, 0.03, zr), P3(1, 0, 0), 1.0);
    const dTr = dimension(P3(-hx, 0.03, zr + Rw), P3(hx, 0.03, zr + Rw), P3(0, 0, 1), 0.95);
    dims.add(dWb, dTr);
    const dimsSide = pop(dimension(P3(xo + 0.05, Rw, zf), P3(xo + 0.05, Rw, zr), P3(0, 1, 0), Rw + 1.0, { gap: Rw + 0.15 }));
    group.add(dims, dimsSide);
    const wbText = `軸距 ${Math.round(m.wb * 1000)}`, trText = `輪距 ${Math.round(m.tr * 1000)}`;

    // 重心
    const cgY = 0.85;
    const cg = pop(new THREE.Group());
    const ball = new THREE.Mesh(new THREE.SphereGeometry(0.2, 32, 20), mat.accent);
    ball.position.y = cgY; ball.castShadow = true;
    const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.018, 0.018, cgY, 8), mat.accent);
    stem.position.y = cgY / 2;
    const ring = new THREE.Mesh(new THREE.TorusGeometry(0.34, 0.025, 10, 48), mat.accent);
    ring.rotation.x = Math.PI / 2; ring.position.y = 0.03;
    cg.add(ball, stem, ring);
    group.add(cg);

    // 四輪各扛多少：輪子外側的柱子，越高越重
    const bars = {};
    for (const [key, [x, z]] of Object.entries(corners)) {
      const holder = pop(new THREE.Group());
      const col = new THREE.Mesh(new THREE.BoxGeometry(0.34, 1, 0.34), mat.accent);
      col.position.y = 0.5; col.castShadow = true;
      holder.add(col);
      holder.position.set(x + Math.sign(x) * 0.78, 0, z);
      bars[key] = { holder, col };
      group.add(holder);
    }

    // 力的箭頭：輪胎在接地面推地（藍），慣性推車身（橘）
    const grip = {};
    for (const key of Object.keys(corners)) { grip[key] = arrow(mat.blue, 0.05); group.add(grip[key]); }
    const inertia = arrow(mat.accent, 0.07);
    group.add(inertia);

    // 轉彎那張要把前輪打彎：前輪平均轉角 → 內輪角
    const turnR = (deg) => L / Math.tan(THREE.MathUtils.degToRad(deg));   // 前輪平均轉角 → 轉彎半徑（到車子中線）
    const innerDeg = (deg) => THREE.MathUtils.radToDeg(Math.atan(L / (turnR(deg) - hx)));

    const A = new THREE.Vector3(), B = new THREE.Vector3();
    let shot = null, p = {};
    function update() {
      const is = (...names) => names.includes(shot?.show);
      const labels = [];
      placeFrame();

      // 每個輪子扛多少：先算靜態（重心滑桿），再加上加速、轉彎的重量轉移
      const front = (p.front ?? 45) / 100, left = (p.left ?? 50) / 100;
      const dLong = M * st.ax * H / m.wb;        // 加速：前軸少、後軸多（kg）
      const dLat = M * st.ay * H / m.tr;         // 左轉：左邊（內側）少、右邊（外側）多（kg）
      const loads = {
        fl: M * front * left - dLong / 2 - dLat * front,
        fr: M * front * (1 - left) - dLong / 2 + dLat * front,
        rl: M * (1 - front) * left + dLong / 2 - dLat * (1 - front),
        rr: M * (1 - front) * (1 - left) + dLong / 2 + dLat * (1 - front),
      };
      const shiftZ = st.ax * 0.45, shiftX = st.ay * 0.45;   // 重量往後、往外的方向（示意）
      cg.position.set(-hx + (1 - left) * T + shiftX, 0, zf + (1 - front) * L + shiftZ);

      const showBars = is("loads", "accel", "corner");
      for (const [key, b] of Object.entries(bars)) {
        show(b.holder, showBars);
        const h = Math.max(0.05, loads[key] / 150 * 1.7);
        b.col.scale.y = h; b.col.position.y = h / 2;
        if (showBars) labels.push({ at: [b.holder.position.x, h + 0.35, b.holder.position.z], text: `${Math.round(loads[key])} kg`, tone: "accent" });
      }

      // 加速：後輪往前推地；慣性把重量往後推
      // 轉彎：四個輪胎都往轉彎中心（左邊）推；慣性把重量往外（右邊）推
      for (const [key, [x, z]] of Object.entries(corners)) {
        const a = grip[key];
        let on = false;
        if (is("accel") && z > 0 && st.ax > 0.02) {
          on = true; A.set(x, 0.06, z); B.set(x, 0.06, z - 0.3 - st.ax * 1.4);
        } else if (is("corner") && st.ay > 0.02) {
          on = true;
          const len = 0.25 + Math.max(0, loads[key]) / 150 * st.ay * 1.3;
          A.set(x, 0.06, z); B.set(x - len, 0.06, z);
        }
        show(a, on);
        if (on) a.set(A.clone(), B.clone());
      }
      const ig = is("accel") ? st.ax : is("corner") ? st.ay : 0;
      show(inertia, ig > 0.02);
      if (ig > 0.02) {
        A.set(cg.position.x, cgY + 0.45, cg.position.z);
        B.copy(A).add(is("accel") ? new THREE.Vector3(0, 0, 0.4 + ig * 1.4) : new THREE.Vector3(0.4 + ig * 1.4, 0, 0));
        inertia.set(A.clone(), B.clone());
        labels.push({ at: B.toArray().map((v, i) => v + (i === 1 ? 0.35 : 0)), text: is("accel") ? "重量往後" : "重量往外", tone: "accent" });
        labels.push({ at: is("accel") ? [hx + 0.9, 0.1, zr - 0.9] : [-hx - 1.3, 0.1, 0], text: is("accel") ? "後輪推地往前" : "輪胎往內推", tone: "blue" });
      }

      if (is("dims")) labels.push({ at: dWb.mid.toArray(), text: wbText, tone: "dim" }, { at: dTr.mid.toArray(), text: trText, tone: "dim" });
      if (is("formula")) labels.push({ at: dimsSide.mid.toArray(), text: wbText, tone: "dim" });
      if (is("cg", "formula")) labels.push({ at: [cg.position.x, cgY + 0.6, cg.position.z], text: "重心", tone: "accent" });
      return labels;
    }

    return {
      group,
      shots: {
        // 路線在車子的 +x 側（右邊）。方位角（從 +z 往 +x 量）：
        // hero 41° → frame 65° → top（正上方，畫面方向同側視）→ cg／side 90° → loads／accel 60° → corner 29°
        // 一路只在右側小幅移動，不跑到左邊或車頭前面。
        hero:  { pos: [7.4, 4.6, 8.6],   look: [0, 0.5, 0] },        // 3D：右後上方
        frame: { pos: [8.6, 4.4, 4.0],   look: [0, 0.8, 0] },        // 右側稍後、抬高：看車架從平台升起
        // 正俯視：鏡頭只往 +x 偏一點點，畫面方向跟右側視一樣（車頭朝畫面右邊）：
        // 從 frame 抬頭上去、再低頭下到 cg 側視，車子在畫面上的方向都不變
        top:   { pos: [0.64, 19, -1.2],  look: [0.6, 0, -1.2] },  // 車往畫面左邊移，讓開右側文字欄
        // 正側視（從右邊看，車頭朝畫面右邊）
        cg:    { pos: [17.5, 1.4, 0],    look: [0, 1.0, 0] },
        side:  { pos: [17.5, 1.6, 0],    look: [0, 1.3, 0] },
        loads: { pos: [8.5, 7.4, 4.9],   look: [0, 0.5, 0] },        // 右側抬高：四根柱子都看得到
        accel: { pos: [9.2, 4.9, 5.5],   look: [0, 0.6, 0.2] },      // 同方位、低一點：看得到車頭抬起
        corner:{ pos: [5.6, 6.0, 9.8],   look: [0, 0.6, -0.3] },     // 右後方：看得到左右兩側的柱子和車身側傾
        wide:  { pos: [9.5, 6.2, 11],    look: [0, 0.5, 0] },
      },
      apply(s, params) {
        shot = s; p = params;
        const is = (...names) => names.includes(s.show);
        mat.tire.opacity = 1; mat.tire.depthWrite = true;
        st.riseWant = is("wheels") ? 0 : 1;
        st.axWant = is("accel") ? p.ax ?? 0.6 : 0;
        st.ayWant = is("corner") ? p.ay ?? 0.8 : 0;
        st.spin = is("accel");
        // 轉彎那張要把前輪打彎：交給設計工具的轉向連桿重蓋一次
        const steer = is("corner") ? 10 : 0;
        if (steer !== st.steer) {
          st.steer = steer;
          dc.build(steer ? { steer: Math.round(innerDeg(steer) * 2) / 2 } : {});
        }
        show(dims, is("dims")); show(dimsSide, is("formula"));
        show(cg, is("cg", "loads", "formula", "accel", "corner"));
        return update();
      },
      tick(dt) {
        let moved = false;
        const toward = (key, want, rate) => {
          if (Math.abs(st[key] - want) < 0.002) { if (st[key] !== want) { st[key] = want; moved = true; } return; }
          st[key] += (want - st[key]) * (reduceMotion ? 1 : 1 - Math.pow(rate, dt));
          moved = true;
        };
        // 車架固定 1.2 秒升起／降下
        if (st.rise !== st.riseWant) {
          const step = reduceMotion ? 1 : dt / 1.2;
          st.rise = st.riseWant > st.rise ? Math.min(st.riseWant, st.rise + step) : Math.max(st.riseWant, st.rise - step);
          placeFrame();
        }
        toward("ax", st.axWant, 0.05);
        toward("ay", st.ayWant, 0.05);
        if (st.spin) for (const w of dc.car.wheels) w.rotateX(-dt * (2 + st.ax * 6));
        if (moved) { placeFrame(); return "relabel"; }
      },
    };
  }

  // 工程圖尺寸線：細線、延伸線、兩端箭頭。a、b＝要量的兩點，dir＝尺寸線往哪邊偏（單位向量），dist＝偏多遠。
  // 延伸線從物體外 gap 開始，超出尺寸線 over。回傳的群組帶 mid（尺寸線中點，數字放這裡）。
  function dimension(a, b, dir, dist, { gap = 0.15, over = 0.2 } = {}) {
    const g = new THREE.Group();
    const A = a.clone().addScaledVector(dir, dist), B = b.clone().addScaledVector(dir, dist);
    const line = (p, q) => { const m = tube(p, q, 0.011, mat.ink); m.castShadow = false; g.add(m); };
    line(a.clone().addScaledVector(dir, gap), A.clone().addScaledVector(dir, over));
    line(b.clone().addScaledVector(dir, gap), B.clone().addScaledVector(dir, over));
    const u = B.clone().sub(A).normalize(), head = 0.3;
    line(A.clone().addScaledVector(u, head * 0.8), B.clone().addScaledVector(u, -head * 0.8));
    for (const [tip, d] of [[A, u.clone().negate()], [B, u]]) {
      const cone = new THREE.Mesh(new THREE.ConeGeometry(0.055, head, 16), mat.ink);
      cone.quaternion.setFromUnitVectors(UP, d);
      cone.position.copy(tip).addScaledVector(d, -head / 2);
      g.add(cone);
    }
    g.mid = A.clone().lerp(B, 0.5);
    return g;
  }

  // 兩點之間會動的桿子：set(a, b) 之後跟著伸縮、轉向
  function link(material, r = 0.04) {
    const m = new THREE.Mesh(new THREE.CylinderGeometry(r, r, 1, 14), material);
    m.castShadow = true;
    const dir = new THREE.Vector3();
    m.set = (a, b) => {
      dir.copy(b).sub(a);
      const len = Math.max(0.001, dir.length());
      m.position.copy(a).addScaledVector(dir, 0.5);
      m.quaternion.setFromUnitVectors(UP, dir.normalize());
      m.scale.y = len;
    };
    m.userData.keepScale = true;   // 長度自己管，出現／消失時不要整支縮放
    return m;
  }

  // ── 展品：轉向 ──
  // 同一台車，只講機構：方向盤 → 轉向柱 → 小齒輪／齒條 → 拉桿 → 轉向臂 → 輪子。
  // steer＝前輪平均轉角（度，正＝左轉）。內輪角交給設計工具的連桿去擺；
  // 右轉時把整台車左右鏡射（車子左右對稱，這樣只要算左轉）。
  // 方向盤、小齒輪的轉動是示意：方向盤轉的角度取前輪的 4 倍。
  function steeringExhibit() {
    const group = new THREE.Group();
    const dc = designCar({ scale: 2.7 });
    group.add(dc.holder);
    const S = dc.scale, { m } = dc.car;
    const L = m.wb * S, hx = m.tr * S / 2, zf = -L / 2;
    const RATIO = 4;
    const col = dc.ends("轉向柱"), rk = dc.ends("齒條"), tieL = dc.ends("前左 轉向拉桿"), armL = dc.ends("前左 轉向臂");
    const rackC = mix(rk[0], rk[1]), wheelC = col[1], pinC = col[0], colMid = mix(col[0], col[1]);
    const knuckle = mix(tieL[1], armL[0]);

    // 小齒輪：轉向柱下端的一顆齒輪，跟著方向盤轉
    const colAxis = new THREE.Vector3(...wheelC).sub(new THREE.Vector3(...pinC)).normalize();
    const pinion = new THREE.Group();
    const gear = new THREE.Group();
    const hubM = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, 0.09, 24), mat.accent);
    gear.add(hubM);
    for (let i = 0; i < 10; i++) {
      const t = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.09, 0.05), mat.accent);
      const a = i / 10 * Math.PI * 2;
      t.position.set(Math.cos(a) * 0.115, 0, Math.sin(a) * 0.115);
      t.rotation.y = -a;
      gear.add(t);
    }
    pinion.add(gear);
    pinion.position.set(...pinC);
    pinion.quaternion.setFromUnitVectors(UP, colAxis);
    group.add(pinion);

    // 零件順序（第二張會一個一個亮起來）
    const isRim = (o) => o.userData.role === "steer" && o.geometry?.type === "TorusGeometry";
    const PARTS = [
      { name: "方向盤", has: (o) => isRim(o) || o.userData.name === "方向盤橫桿", at: () => add3(wheelC, [0, 0.5, 0]) },
      { name: "轉向柱", has: (o) => o.userData.name === "轉向柱", at: () => add3(colMid, [0.35, 0.1, 0]) },
      { name: "小齒輪＋齒條", has: (o) => o.userData.name === "齒條" || o.userData.name === "轉向機外殼", pinion: true, at: () => add3(rackC, [0, 0.4, 0]) },
      { name: "拉桿", has: (o) => /轉向拉桿/.test(o.userData.name || ""), at: () => add3(mix(tieL[0], tieL[1]), [0, 0.3, 0]) },
      { name: "轉向臂", has: (o) => /轉向臂/.test(o.userData.name || ""), at: () => add3(armL[0], [0, 0.35, 0]) },
      { name: "前輪", wheel: true, at: () => [-hx - 0.2, m.R * S * 2 + 0.3, zf] },
    ];
    const isFrontWheel = (o) => {
      for (let q = o; q; q = q.parent) if (q === dc.car.wheels[0] || q === dc.car.wheels[1]) return true;
      return false;
    };

    const state = { want: 0, cur: 0, flow: false, flowT: 0, flowI: -1, xray: false, ghostWheel: false };
    const frameGhost = new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.12, depthWrite: false });
    frameGhost.color = mat.ghost.color;
    // 特寫轉向臂時，前輪變半透明（轉向臂、拉桿在輪圈內側，從路線側看會被輪胎擋住）
    const wheelGhost = new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.28, depthWrite: false });
    wheelGhost.color = mat.tire.color;
    // 上色：平常轉向系統橘色、拉桿藍色；第二張只亮目前那一個零件
    function paint() {
      const hi = state.flow ? PARTS[state.flowI] : null;
      dc.car.group.traverse(o => {
        if (!o.isMesh) return;
        if (o.userData.mat0 === undefined) o.userData.mat0 = o.material;
        if (o.userData.role === "frame") { o.material = state.xray ? frameGhost : o.userData.mat0; o.castShadow = !state.xray; return; }
        const k = PARTS.findIndex(p => p.has ? p.has(o) : p.wheel && isFrontWheel(o));
        if (k < 0) { o.material = o.userData.mat0; return; }
        const wheel0 = state.ghostWheel ? wheelGhost : o.userData.mat0;
        if (hi) o.material = PARTS[k] === hi ? mat.accent : (PARTS[k].wheel ? wheel0 : mat.clay);
        else o.material = PARTS[k].wheel ? wheel0 : /轉向拉桿/.test(o.userData.name || "") ? mat.blue : mat.accent;
        if (PARTS[k].wheel) o.castShadow = !state.ghostWheel;
      });
      const pinOn = !hi || hi.pinion;
      gear.children.forEach(c => { c.material = pinOn ? mat.accent : mat.clay; });
    }

    // 輪向線：地面上，每個前輪一條灰線（正前方）＋一支橘色箭頭（輪子現在指的方向）。
    // 從車尾後上方看，兩支箭頭和灰線張開的角度就是前輪轉角，一眼看得出有沒有轉、內輪轉得比較多。
    const AIM = { from: m.R * S + 0.15, to: m.R * S + 2.6, y: 0.14 };   // y：箭頭的錐頭半徑約 0.13，不要插進地面
    const aimRef = [-1, 1].map(s => {
      const g = pop(new THREE.Group());
      g.position.set(s * hx, 0, zf);   // 從輪子那一點長出來
      g.add(tube(new THREE.Vector3(0, 0.025, -AIM.from), new THREE.Vector3(0, 0.025, -AIM.to - 0.3), 0.022, mat.ghost));
      group.add(g);
      return g;
    });
    const aimArrow = [-1, 1].map(() => { const a = arrow(mat.accent, 0.045); group.add(a); return a; });
    function placeAim(a) {   // a＝[左輪, 右輪] 轉角（弧度，正＝左轉，車頭朝 −z）
      [-1, 1].forEach((s, i) => {
        const dir = new THREE.Vector3(-Math.sin(a[i]), 0, -Math.cos(a[i]));
        const c = new THREE.Vector3(s * hx, AIM.y, zf);
        aimArrow[i].set(c.clone().addScaledVector(dir, AIM.from), c.clone().addScaledVector(dir, AIM.to));
      });
    }

    // 阿克曼：從正上方看，兩個前輪各畫一條垂直於輪子的線，再加上後軸的延長線，三條交在同一點（轉彎中心）。
    const rays = pop(new THREE.Group());
    group.add(rays);
    const turnR = (deg) => L / Math.tan(Math.abs(THREE.MathUtils.degToRad(deg)));   // 轉彎中心到車子中線（後軸上）
    function placeRays(deg) {
      rays.children.forEach(c => c.geometry.dispose());
      rays.clear();
      if (Math.abs(deg) < 0.5) return;
      const sgn = Math.sign(deg), y = 0.06, zr = L / 2;
      const C = new THREE.Vector3(-sgn * turnR(deg), y, zr);
      [-1, 1].forEach(s => rays.add(tube(new THREE.Vector3(s * hx, y, zf), C, 0.03, mat.accent)));
      rays.add(tube(new THREE.Vector3(sgn * hx, y, zr), C, 0.03, mat.ghost));
      const dot = new THREE.Mesh(new THREE.SphereGeometry(0.16, 20, 12), mat.accent);
      dot.position.copy(C);
      rays.add(dot);
      rays.children.forEach(c => { c.castShadow = false; });
    }

    const angles = (deg) => {   // → [左輪, 右輪] 的轉角（弧度）
      const d = THREE.MathUtils.degToRad(deg);
      if (Math.abs(d) < 0.002) return [0, 0];
      const R = L / Math.tan(Math.abs(d));
      const inner = Math.atan(L / (R - hx)), outer = Math.atan(L / (R + hx));
      return d > 0 ? [inner, outer] : [-outer, -inner];
    };
    const tmpQ = new THREE.Quaternion(), tmpV = new THREE.Vector3();
    function pose() {
      const a = angles(state.cur);
      const inner = Math.max(Math.abs(a[0]), Math.abs(a[1]));
      dc.holder.scale.x = state.cur < 0 ? -S : S;
      const before = dc.car;
      dc.build({ steer: Math.round(THREE.MathUtils.radToDeg(inner) * 2) / 2 });
      // 方向盤繞轉向柱轉（車子鏡射時，方向自然反過來）
      const ang = THREE.MathUtils.degToRad(Math.abs(state.cur) * RATIO);
      const W = new THREE.Vector3(...wheelC).divideScalar(S), axis = colAxis.clone();
      dc.car.group.traverse(o => {
        if (!o.isMesh || o.userData.spun || !(isRim(o) || o.userData.name === "方向盤橫桿")) return;
        tmpQ.setFromAxisAngle(axis, -ang);
        o.position.sub(W).applyQuaternion(tmpQ).add(W);
        o.quaternion.premultiply(tmpQ);
        o.userData.spun = true;
      });
      gear.rotation.y = -THREE.MathUtils.degToRad(state.cur * RATIO);
      placeAim(angles(state.cur));
      if (state.rays) placeRays(state.cur);
      if (dc.car !== before) paint();
    }
    pose(); paint();

    return {
      group,
      // 這一站在路線右邊：觀眾站在路線上（本地 −x 側）往右看。
      // 機構特寫都留在左側（−x），只是越來越靠近；講「前輪轉了」才換到車尾後上方（+z、+y）往車頭看。
      shots: {
        hero:   { pos: [-8.8, 4.8, 5.4], look: [0, 0.6, -0.4] },
        mech:   { pos: add3(colMid, [-3.8, 2.7, 3.4]), look: add3(colMid, [0, -0.1, -0.3]) },
        column: { pos: add3(colMid, [-2.6, 1.9, 2.5]), look: add3(colMid, [0, 0.1, 0]) },
        rack:   { pos: add3(rackC, [-1.4, 2.0, 2.1]), look: add3(rackC, [0, 0.05, 0]) },
        arm:    { pos: add3(knuckle, [-1.6, 2.2, 1.9]), look: add3(knuckle, [0.15, 0, -0.15]) },
        // 後視圖：從車尾、稍微往上，往車頭看。畫面左右＝車的左右，兩個前輪和地上的輪向線都在畫面裡
        rear:   { pos: [0, 9.0, 8.6], look: [0, 0, -2.4] },
        // 阿克曼俯視：轉彎中心在路線側（−x）的後軸延長線上。畫面上方＝車頭，鏡頭稍往 +z 偏
        top:    { pos: [-2.4, 30, 0.9], look: [-2.4, 0, 0.4] },
        wide:   { pos: [-10.5, 6.2, 8.5], look: [0, 0.5, 0] },
      },
      apply(shot, p) {
        const is = (...names) => names.includes(shot.show);
        mat.tire.opacity = 1; mat.tire.depthWrite = true;
        state.want = p.steer ?? shot.steer ?? 0;
        const flow = is("parts");
        const xray = is("rack", "arm");   // 近看齒條、拉桿時，車架變淡，不擋住
        const ghostWheel = is("arm");     // 近看轉向臂時，前輪變半透明
        const aim = is("arm", "all");     // 講「前輪轉了」的那幾張：地上畫輪向線
        aimRef.forEach(g => show(g, aim)); aimArrow.forEach(a => show(a, aim));
        state.rays = is("ackermann");
        show(rays, state.rays);
        if (flow !== state.flow || xray !== state.xray || ghostWheel !== state.ghostWheel) {
          state.flow = flow; state.xray = xray; state.ghostWheel = ghostWheel; state.flowT = 0; state.flowI = flow ? 0 : -1; paint();
        }
        const labels = [];
        const a = angles(state.want);
        const deg = (r) => `${Math.round(Math.abs(THREE.MathUtils.radToDeg(r)))}°`;
        if (flow) {
          const P_ = PARTS[state.flowI];
          labels.push({ at: P_.at(), text: `${state.flowI + 1}　${P_.name}`, tone: "accent" });
        }
        if (is("column")) {
          labels.push({ at: add3(wheelC, [0, 0.5, 0]), text: "方向盤", tone: "accent" },
                      { at: add3(colMid, [0.35, 0.1, 0]), text: "轉向柱", tone: "accent" });
        }
        if (is("rack")) {
          const mm = Math.abs(Math.round((dc.car.fr.steer.rackShift || 0) * 1000));
          labels.push({ at: add3(pinC, [0.25, 0.35, 0]), text: "小齒輪", tone: "accent" },
                      { at: add3(rackC, [0, 0.45, 0.35]), text: `齒條移動 ${mm} mm`, tone: "accent" });
        }
        if (is("arm")) {
          labels.push({ at: add3(mix(tieL[0], tieL[1]), [0, 0.3, 0]), text: "拉桿", tone: "blue" },
                      { at: add3(armL[0], [0, 0.35, 0]), text: "轉向臂", tone: "accent" },
                      { at: [-hx - 0.4, 0.2, zf - 1.0], text: `左前輪 ${deg(a[0])}`, tone: "accent" });
        }
        if (is("ackermann") && Math.abs(state.want) >= 0.5) {
          const sgn = Math.sign(state.want);
          labels.push({ at: [-sgn * turnR(state.want), 0.4, L / 2 + 0.9], text: "轉彎中心", tone: "accent" },
                      { at: [-hx - 0.3, 0.4, zf - 1.1], text: `左前輪 ${deg(a[0])}`, tone: "accent" },
                      { at: [hx + 0.3, 0.4, zf - 1.1], text: `右前輪 ${deg(a[1])}`, tone: "accent" });
        }
        if (is("all")) {
          labels.push({ at: [-hx - 0.5, 0.35, zf - AIM.to * 0.75], text: `左前輪 ${deg(a[0])}`, tone: "accent" },
                      { at: [hx + 0.5, 0.35, zf - AIM.to * 0.75], text: `右前輪 ${deg(a[1])}`, tone: "accent" });
        }
        pose();
        return labels;
      },
      tick(dt) {
        let relabel = false;
        if (state.flow) {
          state.flowT += dt;
          const i = Math.floor(state.flowT / 1.3) % PARTS.length;
          if (i !== state.flowI) { state.flowI = i; paint(); relabel = true; }
        }
        if (Math.abs(state.want - state.cur) >= 0.01) {
          state.cur += (state.want - state.cur) * (reduceMotion ? 1 : 1 - Math.pow(0.004, dt));
          if (Math.abs(state.want - state.cur) < 0.05) state.cur = state.want;
          pose();
          relabel = true;
        }
        if (relabel) return "relabel";
      },
    };
  }

  // ── 展品：懸吊（同一台車的前輪，畫面上是右前角） ──
  // 整台車左右鏡射（holder.scale.x 取負）：設計工具的「前左」角落就出現在右邊（+x），
  // 正好是路線經過、靠中線的那一側；講行程、外傾角時鏡頭再走到這個角的正前方。
  // 雙 A 臂：上下兩支 A 臂把轉向節接到車架，避震器（彈簧＋阻尼）撐在下 A 臂和車架之間。
  // 左前角的 A 臂上藍色、避震器上橘色，其他三個角是灰的。輪子怎麼動交給設計工具的連桿去算。
  // 動畫要順：每 5 mm 預先蓋好一台（進到這一站才開始蓋，一幀蓋一台），播放時只切換顯示哪一台。
  // 另外示範第二種做法：推桿＋搖臂，把彈簧移到車身裡面（這部分是學院自己畫的示意）。
  function suspensionExhibit() {
    const group = new THREE.Group();
    const corner = "前左";
    const S = 3.6;
    const holder = new THREE.Group();
    holder.scale.set(-S, S, S);   // 鏡射：前左 → 畫面上的右前
    group.add(holder);
    const kit = createCarKit(THREE, carMat);
    const paint = (o) => {
      const n = o.userData.name || "";
      if (!n.startsWith(corner)) return null;
      if (n.includes("避震器")) return mat.accent;
      if (n.includes("A 臂")) return mat.blue;
      return null;
    };
    function makeCar(over) {
      const car = kit.buildCar({ ...carSaved, ...over }, { driver: false });
      car.group.traverse(o => {
        if (!o.isMesh) return;
        o.castShadow = true;
        const m2 = paint(o);
        if (m2) o.material = m2;
      });
      car.group.visible = false;
      holder.add(car.group);
      return car;
    }
    const partOf = (car, name) => { let f = null; car.group.traverse(o => { if (!f && o.userData.name === name) f = o; }); return f; };

    // 預先蓋好的姿態：bump −50…60 mm，每 5 mm 一台
    const STEP = 5, KEYS = [];
    for (let b = -50; b <= 60; b += STEP) KEYS.push(b);
    const cache = new Map();
    let extra = null, extraKey = null;          // 改安裝點那一張：照滑桿另外蓋
    const base = makeCar({ bump: 0 });
    cache.set(0, base);
    let shown = base;
    base.group.visible = true;
    const { m } = base;
    const cx = m.tr / 2 * S, cz = m.zf * S, R = m.R * S;
    const C = [cx, R, cz];                    // 左前輪心（靜止）
    const toX = (v) => [-v.x * S, v.y * S + holder.position.y, v.z * S];
    function showCar(car) {
      if (car === shown) return;
      shown.group.visible = false;
      car.group.visible = true;
      shown = car;
    }
    const nearest = (mm) => Math.max(KEYS[0], Math.min(KEYS[KEYS.length - 1], Math.round(mm / STEP) * STEP));

    // 路面：輪子底下那一塊會升降
    const road = new THREE.Mesh(new THREE.BoxGeometry(1.5, 1, 1.7), mat.soft);
    road.receiveShadow = true;
    group.add(road);

    // 安裝點：八個硬點畫成小球
    const marks = new THREE.Group();
    holder.add(marks);
    const markMat = mat.accent;
    function placeMarks(car) {
      marks.clear();
      const pts = [];
      for (const n of ["下 A 臂 前腳", "下 A 臂 後腳", "上 A 臂 前腳", "上 A 臂 後腳"]) {
        const o = partOf(car, `${corner} ${n}`); if (o) pts.push(o.userData.a, o.userData.b);
      }
      const sh = partOf(car, `${corner} 避震器`); if (sh) pts.push(sh.userData.a, sh.userData.b);
      for (const p of pts) {
        const b = new THREE.Mesh(new THREE.SphereGeometry(0.016, 18, 12), markMat);
        b.position.copy(p); marks.add(b);
      }
    }
    marks.visible = false;

    // 推桿＋搖臂（設計工具的前左角＝畫面上的右前，車上座標 m）：FSAE 常見的 pushrod 配置
    // 推桿從下 A 臂外端往上、往內斜，頂到車架上方的搖臂；搖臂繞前後方向的軸轉，
    // 另一端推著橫躺在車架上方的避震器（彈簧套在外面），避震器另一端鎖在車子中線附近。
    // 輪子上去 → 推桿往上頂 → 搖臂轉 → 避震器被壓短。
    const push = new THREE.Group();
    push.visible = false;
    holder.add(push);
    const pRod = link(mat.blue, 0.008), rockA = link(mat.accent, 0.012), rockB = link(mat.accent, 0.012), rockC = link(mat.accent, 0.008);
    const dBody = link(mat.clay, 0.02), dShaft = link(mat.clay, 0.007);
    const coils = Array.from({ length: 8 }, () => {
      const c = new THREE.Mesh(new THREE.TorusGeometry(0.028, 0.0045, 8, 28), mat.accent);
      push.add(c); return c;
    });
    const knob = (r) => new THREE.Mesh(new THREE.SphereGeometry(r, 14, 10), mat.clay);
    const pivotM = new THREE.Mesh(new THREE.CylinderGeometry(0.017, 0.017, 0.05, 16).rotateX(Math.PI / 2), mat.clay);
    const endA = knob(0.012), endB = knob(0.012), endP = knob(0.011), endIn = knob(0.014);
    push.add(pRod, rockA, rockB, rockC, dBody, dShaft, pivotM, endA, endB, endP, endIn);
    const PR = (() => {
      const lo = partOf(base, `${corner} 下 A 臂 前腳`), lo2 = partOf(base, `${corner} 下 A 臂 後腳`);
      const at = (car) => {   // 推桿下端：下 A 臂靠外 10% 的地方
        const l = partOf(car, `${corner} 下 A 臂 前腳`), l2 = partOf(car, `${corner} 下 A 臂 後腳`);
        const lbj = l.userData.a, inn = l.userData.b.clone().lerp(l2.userData.b, 0.5);
        return lbj.clone().lerp(inn, 0.1).add(new THREE.Vector3(0, 0.012, 0));
      };
      const P0 = at(base), z = P0.z;
      // 車架上緣（前軸那一圈）：從車架管裡找 y 最高、z 接近前軸的那一根
      let rail = null;
      base.group.traverse(o => {
        const u = o.userData;
        if (u.role !== "frame" || !u.a || !u.b) return;
        for (const q of [u.a, u.b]) if (q.x < 0 && Math.abs(q.z - z) < 0.03 && (!rail || q.y > rail.y)) rail = q.clone();
      });
      rail = rail || new THREE.Vector3(-0.24, 0.56, z);
      const O = new THREE.Vector3(rail.x + 0.025, rail.y + 0.06, z);            // 搖臂支點：車架上緣再高一點
      const dir = O.clone().sub(P0).normalize();                                  // 推桿大致的方向（往上、往內）
      const perp = new THREE.Vector3(-dir.y, dir.x, 0);                           // 垂直推桿、朝外上方
      if (perp.x > 0) perp.negate();
      const A0 = O.clone().addScaledVector(perp, 0.07);                           // 搖臂接推桿的那一端
      const B0 = O.clone().add(new THREE.Vector3(0, 0.075, 0));                   // 搖臂接避震器的那一端（往上）
      const In = new THREE.Vector3(0.06, B0.y, z);                                // 避震器另一端：過了中線一點
      // 搖臂支架、避震器支架、上緣橫管（只在這張出現）
      push.add(tube(rail.clone().setY(rail.y - 0.005), O, 0.01, mat.clay));
      push.add(tube(new THREE.Vector3(-rail.x, rail.y, z), rail, 0.012, mat.clay));
      push.add(tube(new THREE.Vector3(In.x, rail.y, z), In, 0.01, mat.clay));
      return { at, O, A0, B0, In, Lp: P0.distanceTo(A0), L0: B0.distanceTo(In) };
    })();
    const rot = (p, d) => p.clone().sub(PR.O).applyAxisAngle(new THREE.Vector3(0, 0, 1), d).add(PR.O);
    function posePush(car) {
      const P = PR.at(car);
      // 找搖臂轉角：讓推桿長度不變
      let lo = -1.4, hi = 1.4;
      const f = (d) => rot(PR.A0, d).distanceTo(P) - PR.Lp;
      for (let i = 0; i < 40; i++) { const mid = (lo + hi) / 2; if (Math.sign(f(mid)) === Math.sign(f(lo))) lo = mid; else hi = mid; }
      const d = (lo + hi) / 2, A = rot(PR.A0, d), B = rot(PR.B0, d);
      pRod.set(P, A);
      rockA.set(PR.O, A); rockB.set(PR.O, B); rockC.set(A, B);
      // 避震器：外筒鎖在中線那一端，活塞桿從搖臂那一端插進去；彈簧套在搖臂那一半，壓短時圈距變密
      const len = B.distanceTo(PR.In), u = PR.In.clone().sub(B).normalize();
      const bodyStart = PR.In.clone().addScaledVector(u, -PR.L0 * 0.55);
      dBody.set(bodyStart, PR.In); dShaft.set(B, bodyStart.clone().addScaledVector(u, 0.02));
      const perch = bodyStart.clone().addScaledVector(u, 0.03);
      const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), u);
      coils.forEach((c, i) => {
        c.position.copy(B).addScaledVector(u, 0.012).lerp(perch, i / (coils.length - 1));
        c.quaternion.copy(q);
      });
      pivotM.position.copy(PR.O); endA.position.copy(A); endB.position.copy(B); endP.position.copy(P); endIn.position.copy(PR.In);
      return { len, A, B, P };
    }
    let pushPose = null;

    const state = { want: 0, cur: 0, mode: "bump", zeta: 0.1, x: 0, v: 0, clock: 0, push: false, active: false, building: 0 };
    let shotShow = null;
    function pose(mm, bodyMoves) {
      const car = extra || cache.get(nearest(mm)) || shown;
      showCar(car);
      // 這一台的避震器：推桿模式時藏起來，改看推桿＋搖臂
      car.group.traverse(o => { if ((o.userData.name || "") === `${corner} 避震器`) o.visible = !state.push; });
      if (state.push) pushPose = posePush(car);
      const d = mm / 1000 * S;
      // 路面凸起時輪子上去、車身不動；彈跳時輪子留在地上、車身上下
      holder.position.y = bodyMoves ? -d : 0;
      const roadTop = 0.02 + (bodyMoves ? 0 : d);
      road.scale.y = Math.max(0.02, roadTop);
      road.position.set(cx, roadTop / 2 - 0.01, cz);
    }
    pose(0, false);
    const camber = () => {
      const w = shown.wheels[0];
      const axle = new THREE.Vector3(-1, 0, 0).applyQuaternion(w.quaternion);
      return -THREE.MathUtils.radToDeg(Math.asin(axle.y));   // 正＝輪子上緣往外倒
    };
    const ends = (name) => { const o = partOf(shown, `${corner} ${name}`); return o ? [toX(o.userData.a), toX(o.userData.b)] : null; };

    return {
      group,
      shots: {
        // C＝右前輪心。路線在 +x 側：全貌、零件從右前方斜看（路線那一側），
        // 講行程、彈簧、避震器、外傾角時走到車頭正前方（−z），略高於輪心，看得到輪子上下、A 臂擺動、輪子傾斜。
        hero:  { pos: add3(C, [6.2, 4.0, -4.6]),  look: add3(C, [-1.4, 0, 0.4]) },
        parts: { pos: add3(C, [3.6, 1.6, -5.6]),  look: add3(C, [-0.7, 0.35, 0.1]) },
        // 正前方：鏡頭和看的點在同一個 x，只往前退，接近正視圖
        front: { pos: add3(C, [-0.2, 0.9, -8.6]), look: add3(C, [-0.2, 0.25, 0]) },
        mount: { pos: add3(C, [1.8, 3.0, -5.4]),  look: add3(C, [-0.9, 0.1, 0.1]) },
        // 從右前方、稍高看：輪子、推桿、車架上方的搖臂和避震器都在畫面裡
        push:  { pos: add3(C, [3.2, 3.8, -7.8]),  look: add3(C, [-1.0, 0.75, 0]) },
        wide:  { pos: [8.5, 5.6, 10.5], look: [0, 1.2, 0] },
      },
      apply(shot, p) {
        const is = (...names) => names.includes(shot.show);
        shotShow = shot.show;
        state.active = true;
        mat.tire.opacity = 1; mat.tire.depthWrite = true;
        state.mode = is("damper") ? "bounce" : "bump";
        state.zeta = p.zeta ?? 0.1;
        state.push = is("pushrod");
        push.visible = state.push;
        const mm = is("plain", "mount") ? 0 : p.bump ?? shot.bump ?? 0;
        state.want = mm;

        // 改安裝點：照滑桿另外蓋一台（靜止姿態）
        if (is("mount")) {
          const at = p.shockAt ?? 75;
          if (at === 75) { extra = null; extraKey = null; }
          else if (extraKey !== at) {
            if (extra) { holder.remove(extra.group); extra.group.traverse(o => o.geometry?.dispose()); }
            extra = makeCar({ bump: 0, shockAt: at }); extraKey = at;
          }
        } else if (extra) { if (shown === extra) showCar(base); holder.remove(extra.group); extra.group.traverse(o => o.geometry?.dispose()); extra = null; extraKey = null; }
        pose(state.cur, false);
        marks.visible = is("mount");
        if (is("mount")) placeMarks(shown);

        const labels = [];
        if (is("parts")) {
          const up = ends("上 A 臂 前腳"), lo = ends("下 A 臂 前腳"), kn = ends("轉向節"), sh = ends("避震器");
          labels.push({ at: add3(mix(up[0], up[1]), [0, 0.25, 0]), text: "上 A 臂", tone: "blue" },
                      { at: add3(mix(lo[0], lo[1]), [0, -0.25, 0]), text: "下 A 臂", tone: "blue" },
                      { at: add3(mix(kn[0], kn[1]), [0.35, 0, 0]), text: "立柱", tone: "soft" },
                      { at: add3(mix(sh[0], sh[1], 0.75), [-0.2, 0, 0]), text: "彈簧", tone: "accent" },
                      { at: add3(sh[0], [0, 0.3, 0]), text: "避震器", tone: "accent" });
        }
        if (is("spring")) {
          const sh = ends("避震器");
          labels.push({ at: add3(sh[0], [0, 0.5, 0]), text: `彈簧多出的力 ${mm >= 0 ? "+" : "−"}${Math.abs(Math.round(mm * 30))} N`, tone: "accent" });
        }
        if (is("camber")) {
          const deg = camber();
          const up = ends("上 A 臂 前腳"), lo = ends("下 A 臂 前腳");
          labels.push({ at: add3(C, [0.2, R + 0.6, 0]), text: `外傾角 ${deg <= -0.05 ? "−" : deg >= 0.05 ? "+" : ""}${Math.abs(deg).toFixed(1)}°`, tone: "accent" });
          if (up && lo) labels.push({ at: add3(mix(up[0], up[1]), [0, 0.25, 0]), text: "上 A 臂（短）", tone: "blue" },
                                    { at: add3(mix(lo[0], lo[1]), [0, -0.25, 0]), text: "下 A 臂（長）", tone: "blue" });
        }
        if (is("mount")) {
          const k = shown.fr.kin["前"], mr = Math.abs(k.mr || 0);
          const lo = ends("下 A 臂 前腳"), sh = ends("避震器");
          labels.push({ at: add3(lo[1], [0, 0.35, 0]), text: "樞軸鎖在車架節點", tone: "blue" },
                      { at: add3(sh[1], [0, -0.35, 0]), text: `避震下端 ${p.shockAt ?? 75}%`, tone: "accent" },
                      { at: add3(sh[0], [0, 0.4, 0]), text: `槓桿比 ${mr.toFixed(2)}　輪上剛性 = 彈簧 × ${(mr * mr).toFixed(2)}`, tone: "accent" });
        }
        if (is("pushrod") && pushPose) {
          const { A, B, P, len } = pushPose;
          const cmp = Math.max(0, Math.round((PR.L0 - len) * 1000));
          labels.push({ at: add3(toX(P.clone().lerp(A, 0.45)), [0.45, 0, 0]), text: "推桿", tone: "blue" },
                      { at: add3(toX(PR.O), [0.55, 0.15, 0]), text: "搖臂", tone: "accent" },
                      { at: add3(toX(B.clone().lerp(PR.In, 0.5)), [0, 0.4, 0]), text: cmp ? `避震器壓縮 ${cmp} mm` : "避震器", tone: "accent" });
        }
        if (is("bump", "spring", "camber", "pushrod") && mm > 0) labels.push({ at: add3(C, [1.1, -R + 0.2, 0]), text: `凸起 ${mm} mm`, tone: "soft" });
        return labels;
      },
      tick(dt) {
        // 進到這一站才開始預先蓋，一幀一台
        if (state.active && cache.size < KEYS.length) {
          const k = KEYS.find(b => !cache.has(b));
          cache.set(k, makeCar({ bump: k }));
        }
        if (state.mode === "bounce") {
          // 質量–彈簧–阻尼：每 3.6 秒被路面頂一下，看幾下才停（x 單位 mm）
          state.clock += dt;
          const w0 = Math.PI * 2 * 1.5;
          if (state.clock > 3.6) { state.clock = 0; state.v = 45 * w0; }
          const acc = -w0 * w0 * state.x - 2 * state.zeta * w0 * state.v;
          state.v += acc * dt; state.x += state.v * dt;
          state.cur = 0;
          pose(reduceMotion ? 0 : state.x, true);
          return;
        }
        if (state.x !== 0 || state.v !== 0) { state.x = 0; state.v = 0; state.clock = 3; state.cur = state.want + 1; }
        if (Math.abs(state.want - state.cur) < 0.05) {
          if (state.cur !== state.want) { state.cur = state.want; pose(state.cur, false); return "relabel"; }
          return;
        }
        state.cur += (state.want - state.cur) * (reduceMotion ? 1 : 1 - Math.pow(0.004, dt));
        pose(state.cur, false);
      },
    };
  }

  // ── 展品：煞車與動力 ──
  // 同一台車上的兩條路線：
  //   煞車（藍）：踏板 → 主缸 → 油管 → 卡鉗夾住碟盤
  //   動力（橘）：電池 → 馬達控制器 → 馬達 → 鏈條 → 後軸
  // 每一步只顯示其中一條，畫面才不會擠。車子像架在架上：輪子會轉，車不會走。
  function drivetrainExhibit() {
    const group = new THREE.Group();
    const L = 3.6, T = 2.8, WR = 0.55;
    const zf = -L / 2, zr = L / 2, hx = T / 2;
    const P = (x, y, z) => new THREE.Vector3(x, y, z);
    const brakeParts = pop(new THREE.Group()), powerParts = pop(new THREE.Group());
    group.add(brakeParts, powerParts);

    // 車身骨架：前軸、後軸（傳動軸）、中樑
    group.add(tube(P(-hx + 0.25, 0.32, zf), P(hx - 0.25, 0.32, zf), 0.035, mat.soft));
    group.add(tube(P(-hx + 0.2, WR, zr), P(hx - 0.2, WR, zr), 0.04, mat.soft));
    group.add(tube(P(0, 0.32, zf - 0.9), P(0, 0.32, zr - 0.3), 0.035, mat.soft));

    const wheels = [];
    for (const [sx, z] of [[-1, zf], [1, zf], [-1, zr], [1, zr]]) {
      const w = makeWheel(WR);
      w.position.set(sx * hx, WR, z);
      if (sx < 0) w.rotation.y = Math.PI;
      group.add(w);
      wheels.push({ w, rear: z > 0 });
    }

    // 煞車：每個輪子內側一片碟盤加一個卡鉗
    const discMat = new THREE.MeshStandardMaterial({ roughness: 0.45, metalness: 0.5 });
    discMat.color = mat.clay.color;
    const pads = [];
    for (const [sx, z] of [[-1, zf], [1, zf], [-1, zr], [1, zr]]) {
      const x = sx * (hx - 0.42);
      const disc = new THREE.Mesh(new THREE.CylinderGeometry(0.38, 0.38, 0.045, 48), discMat);
      disc.rotation.z = Math.PI / 2;
      disc.position.set(x, WR, z);
      disc.castShadow = true;
      const caliper = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.2, 0.34), mat.blue);
      caliper.position.set(x, WR + 0.34, z);
      caliper.castShadow = true;
      brakeParts.add(disc, caliper);
      // 來令片：碟盤兩側各一片，踩煞車時往中間夾
      for (const side of [-1, 1]) {
        const pad = new THREE.Mesh(new THREE.BoxGeometry(0.035, 0.16, 0.26), mat.accent);
        pad.position.set(x, WR + 0.24, z);
        brakeParts.add(pad);
        pads.push({ pad, x, side });
      }
    }
    // 踏板、主缸、油管
    const pedalZ = zf - 0.85;
    const makePedal = (x, material) => {
      const pivot = new THREE.Group();
      pivot.position.set(x, 0.14, pedalZ);
      const arm = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.62, 0.05), mat.clay);
      arm.position.y = 0.31;
      const plate = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.2, 0.05), material);
      plate.position.set(0, 0.6, 0.03);
      arm.castShadow = plate.castShadow = true;
      pivot.add(arm, plate);
      return pivot;
    };
    const brakePedal = makePedal(-0.18, mat.blue), gasPedal = makePedal(0.2, mat.accent);
    group.add(brakePedal, gasPedal);
    const master = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.08, 0.42, 20), mat.blue);
    master.rotation.x = Math.PI / 2;
    master.position.set(-0.18, 0.42, pedalZ - 0.32);
    brakeParts.add(master);
    const line = (a, b) => brakeParts.add(tube(a, b, 0.022, mat.blue));
    const hubF = P(-0.18, 0.2, zf), hubR = P(-0.18, 0.2, zr - 0.35);
    line(P(-0.18, 0.42, pedalZ - 0.1), P(-0.18, 0.2, pedalZ + 0.15)); line(P(-0.18, 0.2, pedalZ + 0.15), hubF); line(hubF, hubR);
    for (const sx of [-1, 1]) {
      line(hubF, P(sx * (hx - 0.42), 0.2, zf)); line(P(sx * (hx - 0.42), 0.2, zf), P(sx * (hx - 0.42), WR + 0.26, zf));
      line(hubR, P(sx * (hx - 0.42), 0.2, zr - 0.35)); line(P(sx * (hx - 0.42), 0.2, zr - 0.35), P(sx * (hx - 0.42), WR + 0.26, zr - 0.1));
    }

    // 動力：電池、馬達控制器、馬達、鏈條、差速器
    const box = (w, h, d, material) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material); m.castShadow = true; return m; };
    const battery = box(1.2, 0.55, 1.0, mat.accent);        battery.position.set(0, 0.68, 0.2);
    const inverter = box(0.46, 0.3, 0.4, mat.clay);         inverter.position.set(0.55, 0.62, 1.12);
    const motor = new THREE.Mesh(new THREE.CylinderGeometry(0.27, 0.27, 0.52, 36), mat.accent);
    motor.rotation.z = Math.PI / 2; motor.position.set(-0.42, WR, 1.15); motor.castShadow = true;
    const spin = (r, len, x, z, material) => {   // 會轉的圓盤，上面一顆記號看得出在轉
      const g = new THREE.Group();
      const d = new THREE.Mesh(new THREE.CylinderGeometry(r, r, len, 40), material);
      d.rotation.z = Math.PI / 2; d.castShadow = true;
      const dot = new THREE.Mesh(new THREE.SphereGeometry(Math.min(0.05, r * 0.35), 14, 10), mat.accent);
      dot.position.set(len / 2, r * 0.7, 0);
      g.add(d, dot);
      g.position.set(x, WR, z);
      return g;
    };
    const small = spin(0.1, 0.07, 0.02, 1.15, mat.soft), big = spin(0.34, 0.07, 0.02, zr, mat.soft);
    const diff = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 0.34, 30), mat.clay);
    diff.rotation.z = Math.PI / 2; diff.position.set(0.28, WR, zr);
    powerParts.add(battery, inverter, motor, small, big, diff);
    powerParts.add(tube(P(-0.16, WR, 1.15), P(0.06, WR, 1.15), 0.035, mat.soft));
    powerParts.add(tube(P(0.02, WR + 0.1, 1.15), P(0.02, WR + 0.34, zr), 0.02, mat.tire));     // 鏈條上段
    powerParts.add(tube(P(0.02, WR - 0.1, 1.15), P(0.02, WR - 0.34, zr), 0.02, mat.tire));     // 鏈條下段
    // 高壓線（橘）：電池 → 控制器 → 馬達
    const hv = [P(0.3, 0.68, 0.7), P(0.55, 0.68, 0.92), P(0.55, 0.62, 1.12), P(0.1, 0.78, 1.15), P(-0.42, WR + 0.27, 1.15)];
    for (let i = 0; i < hv.length - 1; i++) powerParts.add(tube(hv[i], hv[i + 1], 0.03, mat.accent));
    // 訊號線（細、灰）：油門踏板 → 控制器
    const sig = [P(0.2, 0.2, pedalZ), P(0.95, 0.16, pedalZ), P(0.95, 0.16, 1.12), P(0.78, 0.5, 1.12)];
    for (let i = 0; i < sig.length - 1; i++) powerParts.add(tube(sig[i], sig[i + 1], 0.014, mat.soft));
    // 沿著高壓線跑的光點：電往哪邊流
    const flowPath = new THREE.CatmullRomCurve3(hv, false, "catmullrom", 0.1);
    const dots = Array.from({ length: 5 }, () => {
      const d = new THREE.Mesh(new THREE.SphereGeometry(0.06, 16, 12), new THREE.MeshBasicMaterial({ color: 0xffffff }));
      powerParts.add(d);
      return d;
    });

    const state = { throttle: 0, brake: 0, mode: "idle", speed: 0, heat: 0, phase: 0, angle: 0 };
    return {
      group,
      shots: {
        // 車子左右對稱：煞車那幾張全在左側，聚焦左後輪，最多從後面一點看卡鉗
        hero:    { pos: [-8.6, 5.0, 3.4],  look: [0, 0.5, 0] },
        brake:   { pos: [-8.4, 6.2, 3.6],  look: [0, 0.4, -0.6] },
        caliper: { pos: [-3.3, 2.7, zr + 2.3], look: [-hx + 0.5, 0.7, zr - 0.1] },
        // 動力：俯視（車頭朝上），電池 → 控制器 → 馬達的路線一眼看完
        power:   { pos: [0.15, 12.5, 1.5], look: [0.15, 0, 0.1] },
        chain:   { pos: [-2.4, 1.9, 4.5],  look: [0.1, 0.55, 1.3] },
        wide:    { pos: [9.5, 6.2, 11],    look: [0, 0.5, 0] },
      },
      apply(shot, p, reveal) {
        const is = (...names) => names.includes(shot.show);
        const ans = is("draw") && reveal;
        mat.tire.opacity = 1; mat.tire.depthWrite = true;
        const brakeOn = is("plain", "brake", "caliper", "regen", "draw");
        const powerOn = is("plain", "power", "throttle", "gear", "regen", "draw");
        show(brakeParts, brakeOn); show(powerParts, powerOn);
        state.mode = is("caliper") ? "braking" : is("throttle", "gear") ? "driving" : is("regen") ? "regen" : "idle";
        state.brake = is("caliper") ? (p.brake ?? 40) / 100 : 0;
        state.throttle = is("throttle", "gear") ? (p.throttle ?? 40) / 100 : 0;
        const labels = [];
        if (is("brake") || ans) {
          labels.push({ at: [-0.18, 1.15, pedalZ], text: "煞車踏板", tone: "blue" }, { at: [-0.18, 0.75, pedalZ - 0.7], text: "主缸", tone: "blue" },
                      { at: [-0.18, 0.5, 0], text: "油管", tone: "blue" }, { at: [-hx + 0.42, 1.35, zr], text: "卡鉗與碟盤", tone: "blue" });
        }
        if (is("caliper")) {
          labels.push({ at: [-hx + 0.42, 1.2, zr], text: "卡鉗", tone: "blue" }, { at: [-hx + 0.42, 0.2, zr + 0.45], text: "碟盤" });
        }
        if (is("power", "throttle") || ans) {
          labels.push({ at: [0, 1.25, 0.2], text: "電池", tone: "accent" }, { at: [0.75, 1.05, 1.12], text: "馬達控制器" },
                      { at: [-0.75, 1.1, 1.15], text: "馬達", tone: "accent" }, { at: [0.1, 1.2, zr + 0.25], text: "鏈條與差速器", tone: "soft" });
        }
        if (is("throttle")) labels.push({ at: [0.2, 1.15, pedalZ], text: "油門踏板：只送訊號", tone: "soft" });
        if (is("gear")) labels.push({ at: [0.02, 0.95, 1.05], text: "小齒盤", tone: "soft" }, { at: [0.02, 1.2, zr + 0.1], text: "大齒盤", tone: "soft" });
        if (is("regen")) labels.push({ at: [0, 1.25, 0.2], text: "電流回電池", tone: "accent" });
        return labels;
      },
      tick(dt) {
        // 輪速：加速時跟著油門、煞車時被夾慢、回充時維持滾動
        const target = state.mode === "driving" ? state.throttle * 13
          : state.mode === "braking" ? 11 * (1 - state.brake)
          : state.mode === "regen" ? 7 : 0;
        state.speed += (target - state.speed) * (1 - Math.pow(0.05, dt));
        const step = reduceMotion ? 0 : state.speed * dt;
        state.angle += step;
        const allSpin = state.mode !== "driving";
        for (const { w, rear } of wheels) if (rear || allSpin) w.rotation.x -= step;
        big.rotation.x -= step; small.rotation.x -= step * 3.4;

        brakePedal.rotation.x += (-state.brake * 0.5 - brakePedal.rotation.x) * 0.2;
        gasPedal.rotation.x += (-state.throttle * 0.5 - gasPedal.rotation.x) * 0.2;
        for (const { pad, x, side } of pads) pad.position.x = x + side * (0.045 + 0.06 * (1 - state.brake));
        // 碟盤發熱：踩越重、轉越快，越紅
        const heatTarget = state.mode === "braking" ? state.brake * (0.35 + state.speed / 11) : 0;
        state.heat += (heatTarget - state.heat) * (1 - Math.pow(0.2, dt));
        discMat.emissive.setRGB(1, 0.28, 0.05).multiplyScalar(state.heat * 1.6);

        // 電流光點：加速時電池 → 馬達，回充時反過來
        const flow = state.mode === "driving" ? state.throttle : state.mode === "regen" ? -0.5 : 0;
        state.phase = (state.phase + flow * dt * 0.9 + 1) % 1;
        dots.forEach((d, i) => {
          d.visible = Math.abs(flow) > 0.02;
          if (d.visible) d.position.copy(flowPath.getPoint((state.phase + i / dots.length) % 1));
        });
      },
    };
  }

  // ── 展品：還沒做的站（只有一圈虛線） ──
  function ghostExhibit(r) {
    const group = new THREE.Group();
    const n = 28;
    for (let i = 0; i < n; i++) {
      const a = i / n * Math.PI * 2;
      const dash = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.03, 0.06), mat.ghost);
      dash.position.set(Math.cos(a) * r * 0.42, 0.02, Math.sin(a) * r * 0.42);
      dash.rotation.y = -a + Math.PI / 2;
      group.add(dash);
    }
    return {
      group,
      shots: { hero: { pos: [r * 1.5, r * 0.9, r * 1.9], look: [0, 0.3, 0] } },
      apply() { return []; },
    };
  }

  function startExhibit() {
    const group = new THREE.Group();
    const dot = new THREE.Mesh(new THREE.CylinderGeometry(0.42, 0.42, 0.06, 40), mat.accent);
    dot.position.y = 0.03;
    group.add(dot);
    return {
      group,
      shots: { hero: { pos: [-4.5, 5.2, 12.5], look: [2.5, -3.2, -26] } },
      apply() { return []; },
    };
  }

  // ── 展品：一整台電動方程式賽車（全部用程式生成） ──
  // 每個零件標上所屬系統（sub），L2 每一課標亮其中一組，其他淡出。
  // 疊在車上的教學圖層（摩擦圓、配重柱、下壓力箭頭）放在 overlay，不參與標亮。
  const CAR_SUBS = ["輪胎", "車體", "空力", "煞車", "動力", "電池", "懸吊"];
  function formulaExhibit() {
    const group = new THREE.Group();
    const body = new THREE.Group(), overlay = new THREE.Group();
    group.add(body, overlay);
    const L = 3.6, T = 2.8, WR = 0.55, M = 280;
    const zf = -L / 2, zr = L / 2, hx = T / 2;
    const subs = Object.fromEntries(CAR_SUBS.map(n => [n, new THREE.Group()]));
    for (const [name, g] of Object.entries(subs)) { g.userData.sub = name; body.add(g); }
    const add = (sub, obj) => { subs[sub].add(obj); return obj; };
    const carbon = new THREE.MeshStandardMaterial({ roughness: 0.45, metalness: 0.2 });
    carbon.color = mat.tire.color;
    const shell = new THREE.MeshStandardMaterial({ roughness: 0.35, metalness: 0.05 });
    shell.color = mat.platform.color;

    // 輪胎
    const corners = [[-hx, zf], [hx, zf], [-hx, zr], [hx, zr]];
    const tires = [];   // 胎溫示範要單獨上色的四顆輪胎
    const wheels = [];  // 轉向（pivot.rotation.y，前輪）＋滾動（w.rotation.x）
    for (const [x, z] of corners) {
      const pivot = new THREE.Group();
      pivot.position.set(x, WR, z);
      const w = makeWheel(WR);
      w.position.set(0, 0, 0);
      if (x < 0) w.rotation.y = Math.PI;   // Euler XYZ：先翻面，再繞父層 x 軸滾動
      pivot.add(w);
      add("輪胎", pivot);
      tires.push({ mesh: w.children[0], x, z, temp: 40 });
      wheels.push({ pivot, w, x, front: z < 0 });
    }
    // 車架
    spaceFrame((a, b, r = 0.045) => add("車體", tube(a, b, r, mat.clay)));
    // 懸吊：A 臂、推桿、立柱
    aArms((a, b, r) => add("懸吊", tube(a, b, r, mat.soft)), hx, zf, zr);
    for (const [x, z] of corners) {
      const s = Math.sign(x);
      add("懸吊", tube(P3(s * (hx - 0.3), 0.34, z), P3(s * 0.55, 0.95, z + (z < 0 ? 0.25 : -0.25)), 0.025, mat.soft));
      const up = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.56, 0.16), mat.soft);
      up.position.set(s * (hx - 0.3), WR, z); up.castShadow = true;
      add("懸吊", up);
    }
    // 煞車：碟盤加卡鉗
    for (const [x, z] of corners) {
      const s = Math.sign(x);
      const disc = new THREE.Mesh(new THREE.CylinderGeometry(0.34, 0.34, 0.04, 44), mat.clay);
      disc.rotation.z = Math.PI / 2; disc.position.set(s * (hx - 0.42), WR, z);
      disc.userData.disc = z < 0 ? "front" : "rear";
      const cal = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.18, 0.3), mat.clay);
      cal.position.set(s * (hx - 0.42), WR + 0.3, z);
      disc.castShadow = cal.castShadow = true;
      add("煞車", disc); add("煞車", cal);
    }

    // 車體：前鼻錐、座艙側板、座椅、方向盤、車手安全帽
    const nose = new THREE.Mesh(new THREE.LatheGeometry(
      Array.from({ length: 14 }, (_, i) => { const t = i / 13; return new THREE.Vector2(0.06 + 0.46 * Math.pow(t, 0.55), (1 - t) * 1.0); }), 40), shell);
    nose.rotation.x = -Math.PI / 2;            // 車頭朝 -z
    nose.scale.set(1, 1, 0.62);
    nose.position.set(0, 0.56, -2.45);
    const tubShape = new THREE.Shape();
    [[-0.47, 2.45], [0.47, 2.45], [0.68, -0.3], [-0.68, -0.3]].forEach(([x, y], i) => i ? tubShape.lineTo(x, y) : tubShape.moveTo(x, y));
    const tub = new THREE.Mesh(new THREE.ExtrudeGeometry(tubShape, { depth: 0.5, bevelEnabled: true, bevelSize: 0.06, bevelThickness: 0.06, bevelSegments: 4 }), shell);
    tub.rotation.x = -Math.PI / 2; tub.position.y = 0.3;
    const pod = (s) => {
      const shape = new THREE.Shape();
      shape.moveTo(0, 0); shape.lineTo(1.55, 0); shape.quadraticCurveTo(1.6, 0.42, 1.2, 0.46); shape.lineTo(0.15, 0.4); shape.quadraticCurveTo(-0.05, 0.3, 0, 0);
      const m = new THREE.Mesh(new THREE.ExtrudeGeometry(shape, { depth: 0.36, bevelEnabled: true, bevelSize: 0.04, bevelThickness: 0.04, bevelSegments: 3 }), shell);
      m.rotation.y = -Math.PI / 2;           // 形狀的 x 沿著 -z
      m.position.set(s > 0 ? 0.68 + 0.36 : -0.68, 0.3, 0.55);
      return m;
    };
    for (const m of [nose, tub, pod(1), pod(-1)]) { m.castShadow = true; add("車體", m); }
    const helmet = new THREE.Mesh(new THREE.SphereGeometry(0.2, 32, 20), mat.clay);
    helmet.position.set(0, 1.28, 0.02); helmet.castShadow = true;
    const visor = new THREE.Mesh(new THREE.SphereGeometry(0.205, 32, 12, Math.PI * 0.7, Math.PI * 0.6, Math.PI * 0.38, Math.PI * 0.22), carbon);
    visor.position.copy(helmet.position);
    const wheelRim = new THREE.Mesh(new THREE.TorusGeometry(0.15, 0.025, 10, 32), carbon);
    wheelRim.position.set(0, 1.02, -0.78); wheelRim.rotation.x = -0.35;
    add("車體", helmet); add("車體", visor); add("車體", wheelRim);

    // 空力：前翼、尾翼（翼形截面沿翼展擠出）
    function foil(chord, thick, span, aoa) {
      const s = new THREE.Shape();
      s.moveTo(0, 0);
      s.bezierCurveTo(chord * 0.3, -thick * 1.3, chord * 0.75, -thick * 1.1, chord, -thick * 0.15);   // 下表面（彎的那一面朝下）
      s.bezierCurveTo(chord * 0.75, thick * 0.1, chord * 0.3, thick * 0.05, 0, 0);
      const g = new THREE.ExtrudeGeometry(s, { depth: span, bevelEnabled: false, curveSegments: 18 });
      g.translate(-chord, 0, -span / 2);
      const m = new THREE.Mesh(g, carbon);
      m.rotation.y = Math.PI / 2;          // 形狀的 x → -z（前緣朝前），擠出方向 → x
      m.rotation.z = -aoa;                 // 後緣往上翹，產生下壓力
      m.castShadow = true;
      return m;
    }
    const plate = (w, h, d) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), carbon); m.castShadow = true; return m; };
    const fwMain = foil(0.62, 0.06, 2.9, 0.08); fwMain.position.set(0, 0.14, -2.75);
    const fwFlap = foil(0.4, 0.04, 2.6, 0.38);  fwFlap.position.set(0, 0.26, -2.25);
    add("空力", fwMain); add("空力", fwFlap);
    for (const s of [-1, 1]) {
      const ep = plate(0.03, 0.42, 1.0); ep.position.set(s * 1.46, 0.27, -2.6); ep.userData.endplate = true; add("空力", ep);
    }
    const rwY = 1.55, rwZ = 2.35;
    const rw1 = foil(0.62, 0.07, 1.75, 0.12); rw1.position.set(0, rwY, rwZ - 0.2);
    const rw2 = foil(0.42, 0.05, 1.75, 0.5);  rw2.position.set(0, rwY + 0.2, rwZ + 0.25);
    const rw3 = foil(0.32, 0.04, 1.75, 0.85); rw3.position.set(0, rwY + 0.42, rwZ + 0.5);
    add("空力", rw1); add("空力", rw2); add("空力", rw3);
    for (const s of [-1, 1]) {
      const ep = plate(0.03, 0.85, 1.05); ep.position.set(s * 0.89, rwY + 0.18, rwZ + 0.15); ep.userData.endplate = true; add("空力", ep);
      add("空力", tube(P3(s * 0.4, 0.82, 2.0), P3(s * 0.4, rwY, rwZ - 0.2), 0.03, carbon));
    }

    // 電池（座椅後方）與動力（後軸前方的馬達、控制器、鏈條）
    const box = (w, h, d, m) => { const b = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), m); b.castShadow = true; return b; };
    const battery = box(0.9, 0.5, 0.95, mat.soft); battery.position.set(0, 0.58, 0.85);
    add("電池", battery);
    const motor = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.22, 0.42, 32), mat.clay);
    motor.rotation.z = Math.PI / 2; motor.position.set(-0.25, 0.5, 1.55); motor.castShadow = true;
    const inverter = box(0.38, 0.2, 0.32, mat.soft); inverter.position.set(0.25, 0.92, 1.45);
    const sprocket = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 0.05, 36), mat.clay);
    sprocket.rotation.z = Math.PI / 2; sprocket.position.set(0.08, WR, zr);
    add("動力", motor); add("動力", inverter); add("動力", sprocket);
    add("動力", tube(P3(-hx + 0.3, WR, zr), P3(hx - 0.3, WR, zr), 0.035, mat.clay));   // 傳動軸
    add("動力", tube(P3(0.08, 0.6, 1.55), P3(0.08, WR + 0.28, zr), 0.018, carbon));
    add("動力", tube(P3(0.08, 0.4, 1.55), P3(0.08, WR - 0.28, zr), 0.018, carbon));

    // 每個網格各自一份材質，才能單獨標亮或淡出；顏色每幀從共用材質讀，跟著主題走
    body.traverse(o => {
      if (!o.isMesh) return;
      let p = o; while (p && !p.userData.sub) p = p.parent;
      o.userData.sub = p.userData.sub;
      o.userData.base = o.material;
      o.material = o.material.clone();
      o.material.transparent = true;
      o.userData.mix = 0;
    });
    // 每個系統的中心：標籤放這裡
    const centres = {};
    for (const [name, g] of Object.entries(subs)) {
      const b = new THREE.Box3().setFromObject(g);
      centres[name] = [b.getCenter(new THREE.Vector3()).x, b.max.y + 0.25, b.getCenter(new THREE.Vector3()).z];
    }
    centres["輪胎"] = [hx, WR * 2 + 0.3, zf];
    centres["煞車"] = [hx - 0.42, WR + 0.75, zf];
    centres["懸吊"] = [-(hx - 0.6), 1.2, zf];

    // ── 教學圖層 ──
    // 摩擦圓：浮在右前輪正上方（從車尾上方看，畫面左右＝車的左右；上＝車頭）
    const ringAt = P3(hx, WR * 2 + 0.25, zf);
    const ring = pop(new THREE.Group());
    const ringSize = new THREE.Group();          // 半徑另外縮放（pop 會蓋掉 ring 自己的 scale）
    const ringLine = new THREE.Mesh(new THREE.TorusGeometry(1.0, 0.03, 8, 96), mat.blue);
    ringLine.rotation.x = Math.PI / 2;
    const ringFill = new THREE.Mesh(new THREE.CircleGeometry(1.0, 64), new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.1, depthWrite: false }));
    ringFill.material.color = mat.blue.color;
    ringFill.rotation.x = -Math.PI / 2;
    ringSize.add(ringLine, ringFill);
    ring.add(ringSize);
    ring.position.copy(ringAt);
    // 負荷敏感度：灰色參考圈＝「μ 不變」時應有的抓地力
    const refRing = pop(new THREE.Group());
    const refSize = new THREE.Group();
    const refLine = new THREE.Mesh(new THREE.TorusGeometry(1.0, 0.018, 8, 96), mat.soft);
    refLine.rotation.x = Math.PI / 2;
    refSize.add(refLine); refRing.add(refSize);
    refRing.position.copy(ringAt).add(P3(0, -0.01, 0));
    const force = arrow(mat.accent, 0.06);
    overlay.add(ring, refRing, force);

    // 「車在跑」的參照物：地面四排短線往車尾流（速度看情境），輪子同步滾動
    const FLOW_SPAN = 13, FLOW_GAP = 1.3;
    const flow = pop(new THREE.Group());
    const dashGeo = new THREE.BoxGeometry(0.07, 0.012, 0.5);
    const dashes = [];
    for (const [x, phase] of [[-3.3, 0.65], [-2.4, 0], [2.4, 0], [3.3, 0.65]]) {
      for (let i = 0; i < FLOW_SPAN / FLOW_GAP; i++) {
        const d = new THREE.Mesh(dashGeo, mat.soft);
        d.position.set(x, 0.012, 0);
        flow.add(d);
        dashes.push({ d, base: i * FLOW_GAP + phase });
      }
    }
    overlay.add(flow);

    // 配重：四輪外側的柱子＋重心球
    const cols = corners.map(([x, z]) => {
      const holder = pop(new THREE.Group());
      const col = new THREE.Mesh(new THREE.BoxGeometry(0.34, 1, 0.34), mat.accent);
      col.position.y = 0.5; col.castShadow = true;
      holder.add(col);
      holder.position.set(x + Math.sign(x) * 0.75, 0, z);
      overlay.add(holder);
      return { holder, col, x, z };
    });
    const cg = pop(new THREE.Mesh(new THREE.SphereGeometry(0.17, 28, 18), mat.accent));
    overlay.add(cg);

    // 下壓力與阻力箭頭
    const dfFront = arrow(mat.blue, 0.07), dfRear = arrow(mat.blue, 0.07), drag = arrow(mat.soft, 0.05);
    const air = arrow(mat.soft, 0.03);           // 翼片下方的氣流（示意方向）
    overlay.add(dfFront, dfRear, drag, air);
    // 迎風面積 A：從正前方看到的車身輪廓（簡化），畫成車尾後方一片半透明的橘色
    const DRAG_Z = zr + 1.55;
    const areaHalf = [[0, 0.1], [1.22, 0.1], [1.22, 0], [1.58, 0], [1.58, 1.1], [1.22, 1.1], [1.22, 0.62],
                      [0.72, 0.85], [0.72, 1.05], [0.9, 1.3], [0.9, 2.15], [0, 2.15]];
    const areaPts = [...areaHalf, ...areaHalf.slice(1, -1).reverse().map(([x, y]) => [-x, y])];
    const areaShape = new THREE.Shape();
    areaPts.forEach(([x, y], i) => i ? areaShape.lineTo(x, y) : areaShape.moveTo(x, y));
    const dragArea = pop(new THREE.Group());
    const areaFill = new THREE.Mesh(new THREE.ShapeGeometry(areaShape),
      new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.22, depthWrite: false, side: THREE.DoubleSide }));
    areaFill.material.color = mat.accent.color;
    const areaEdge = new THREE.LineLoop(new THREE.BufferGeometry().setFromPoints(areaPts.map(([x, y]) => P3(x, y, 0))),
      new THREE.LineBasicMaterial({ transparent: true, opacity: 0.9 }));
    areaEdge.material.color = mat.accent.color;
    dragArea.add(areaFill, areaEdge);
    dragArea.position.set(0, 0, DRAG_Z);
    overlay.add(dragArea);
    // 箭頭長度和力成正比：三支箭頭同一個比例（每 600 N 一公尺）
    const forceLen = (n) => Math.max(0.02, n / 600);

    // 負荷敏感度（示意）：μ = 1.7 − 0.0025 × 負荷（kg），一顆輪胎的抓地力＝負荷 × μ
    const muAt = (kg) => Math.max(0, 1.7 - 0.0025 * kg);
    const gripOf = (kg) => Math.max(0, kg) * muAt(Math.max(0, kg));
    // 四輪負荷：前軸配重 front、重心高 h（m）、側向 g（正＝右彎，重量往左邊 x < 0 搬）
    // 整車轉移 ΔW = M·g·h ÷ 輪距，前後軸依配重分攤；外側輪加、內側輪減
    const TRACK = 1.24;
    const cornerLoads = (front, h, g) => {
      const dW = M * g * h / TRACK;
      return corners.map(([x, z]) => {
        const share = z < 0 ? front : 1 - front;
        return Math.max(0, M * share / 2 + (x < 0 ? 1 : -1) * dW * share);
      });
    };
    // 電池擺放（示意）：電池 60 kg；其他部分 220 kg、重心高 0.29 m、前軸 48％；軸距 1.27 m
    const batteryBase = battery.position.clone();
    const batteryCg = (bh, bpos) => ({
      front: (220 * 0.48 + 60 * (0.40 + bpos / 127)) / M,
      h: (220 * 0.29 + 60 * bh / 100) / M,
    });

    const state = { focus: null, cycle: false, cycleT: 0, cycleI: 0, heat: 0, heatWant: 0, temp: false, tempT: 0, tempLabel: 0, ay: 0,
      run: false, flowV: 0, flowWant: 0, flowZ: 0, roll: 0, steer: 0, steerWant: 0, plate: 1, plateWant: 1,
      bat: batteryBase.clone(), batWant: batteryBase.clone() };
    // 胎溫顏色（像 F1 轉播的胎溫圖）：冷＝藍、工作溫度＝綠、過熱＝紅
    const TEMP_STOPS = [[40, "#3A7BFF"], [62, "#30B0C7"], [72, "#34C759"], [93, "#34C759"], [102, "#FFCC00"], [112, "#FF3B30"]]
      .map(([t, c]) => [t, new THREE.Color(c)]);
    const tempColor = (t, out) => {
      if (t <= TEMP_STOPS[0][0]) return out.copy(TEMP_STOPS[0][1]);
      for (let i = 1; i < TEMP_STOPS.length; i++) {
        const [t1, c1] = TEMP_STOPS[i], [t0, c0] = TEMP_STOPS[i - 1];
        if (t <= t1) return out.copy(c0).lerp(c1, (t - t0) / (t1 - t0));
      }
      return out.copy(TEMP_STOPS[TEMP_STOPS.length - 1][1]);
    };
    const CYCLE = ["輪胎", "車體", "空力", "煞車", "動力"];

    return {
      group,
      shots: {
        hero:     { pos: [9.5, 4.6, 10.5],  look: [0, 0.8, 0] },
        front:    { pos: [-7.8, 3.2, -9.6], look: [0, 0.7, -0.8] },
        rear:     { pos: [7.4, 3.8, 9.8],   look: [0, 0.9, 0.8] },
        side:     { pos: [13.5, 2.0, 0.01], look: [0, 0.9, 0] },
        // 前翼、尾翼：正側視（車頭朝畫面右邊），拉遠一點，留位置給下壓力箭頭
        aero:     { pos: [18, 2.2, 1.0],    look: [0, 1.5, 0.99] },
        top:      { pos: [0.01, 17, 1.6],   look: [0, 0, 0] },
        corner:   { pos: [5.2, 3.6, -5.4],  look: [1.3, 0.3, -1.9] },
        // 輪胎課：全部站在車尾（路線從車尾方向進來），畫面左右＝車的左右，車頭在畫面上方
        chase:    { pos: [3.2, 3.0, 10.5],  look: [0, 0.7, -0.5] },    // 跟車：後方偏右、略高
        rearHigh: { pos: [1.4, 9.2, 8.6],   look: [0, 0.2, -0.5] },    // 後上方：四顆胎溫＋前輪轉角都看得到
        budget:   { pos: [3.0, 6.2, 4.6],   look: [1.2, 0.9, -1.7] },  // 車尾上方看右前輪（目前沒有投影片用）
        // 摩擦圓：右前輪正上方俯視。pos 往 +z 偏 0.15，lookAt 的畫面上方＝−z＝車頭；畫面右＝+x＝車的右邊
        budgetTop:{ pos: [1.4, 11.5, -1.6], look: [1.4, 0, -1.8] },
        frontwing:{ pos: [-4.2, 1.8, -7.6], look: [0, 0.3, -2.6] },
        rearwing: { pos: [5.4, 3.6, 6.8],   look: [0, 1.5, 2.2] },
        wingside: { pos: [8.5, 2.2, 2.6],   look: [0, 1.7, 2.55] },    // 尾翼剖面：正側面近看（端板淡化）
        dragArea: { pos: [6.6, 3.2, 9.0],   look: [0, 1.0, 1.4] },     // 迎風面積：車尾斜後方，看得到面積和阻力箭頭
        brakes:   { pos: [4.8, 1.9, -5.0],  look: [1.0, 0.55, -1.8] },
        battery:  { pos: [5.8, 4.6, 5.2],   look: [0, 0.7, 0.9] },
        batteryLoads: { pos: [7.5, 4.8, 8.0], look: [0, 0.7, 0.4] },
        loads:    { pos: [9.0, 6.6, 9.6],   look: [0, 0.6, 0] },
        loadsRear:{ pos: [4.6, 6.4, 10.2],  look: [0, 0.6, 0] },       // 左右轉移：偏車尾看，左右不會反
      },
      apply(shot, p) {
        const is = (...names) => names.includes(shot.show);
        state.cycle = is("cycle");
        state.focus = state.cycle ? CYCLE[state.cycleI] : shot.focus ?? null;
        const labels = [];
        if (state.focus && is("plain", "cycle")) labels.push({ at: centres[state.focus], text: state.focus, tone: "accent" });

        // 車在跑：地面短線往後流、輪子滾動；轉彎的投影片前輪真的轉過去（正＝左彎）
        state.run = is("run", "friction", "tiretemp", "sensitivity");
        show(flow, state.run);
        state.flowWant = state.run ? 3.0 : 0;
        state.steerWant = 0;

        // 摩擦圓（fx：負＝煞車、正＝加速；fy：負＝左彎、正＝右彎）
        show(ring, is("friction", "sensitivity")); show(force, is("friction"));
        show(refRing, is("sensitivity"));
        if (is("friction")) {
          const fx = (p.fx ?? -60) / 100, fy = (p.fy ?? 60) / 100;
          const used = Math.hypot(fx, fy), k = Math.min(1, 1 / Math.max(used, 1e-6));
          // 地面給輪胎的力：煞車指向車尾（+z）、加速指向車頭（−z）；右彎指向右邊（+x，彎心）
          const tip = ringAt.clone().add(P3(fy * k, 0.03, -fx * k));
          ringSize.scale.setScalar(1);
          force.set(ringAt.clone().add(P3(0, 0.03, 0)), tip);
          ringLine.material = used > 1 ? mat.accent : mat.blue;
          const dir = [fx < -0.04 ? "煞車" : fx > 0.04 ? "加速" : "", fy < -0.04 ? "左彎" : fy > 0.04 ? "右彎" : ""].filter(Boolean).join("＋") || "滑行";
          labels.push({ at: [tip.x, ringAt.y + 0.4, tip.z], text: used > 1 ? `${dir}：超過極限，打滑` : `${dir}：用掉 ${Math.round(used * 100)}%`, tone: used > 1 ? "accent" : "ink" },
                      { at: [hx - 1.3, ringAt.y, zf - 0.95], text: "↑ 車頭", tone: "soft" });   // 俯視時在圓的左上角，不和箭頭標籤重疊
          state.steerWant = -fy * 0.32;                       // 右彎（fy > 0）→ 前輪往右（負角）
          state.flowWant = 3.0 * (1 + 0.7 * fx);              // 煞車變慢、加速變快
        }
        // 負荷敏感度：藍圈＝實際抓地力，灰圈＝μ 不變時應有的抓地力（半徑：每 160 kg 一公尺）
        if (is("sensitivity")) {
          const load = p.load ?? 70, grip = gripOf(load), ideal = load * muAt(70);
          const r = Math.max(0.05, grip / 160), rr = Math.max(0.05, ideal / 160);
          ringSize.scale.setScalar(r); refSize.scale.setScalar(rr);
          ringLine.material = mat.blue;
          labels.push({ at: [hx, ringAt.y + 0.35, zf - Math.max(r, rr) - 0.3], text: `扛 ${Math.round(load)} kg → 抓 ${Math.round(grip)} kg（μ ${muAt(load).toFixed(2)}）`, tone: "blue" },
                      { at: [hx + rr + 0.35, ringAt.y, zf], text: `μ 不變：${Math.round(ideal)} kg`, tone: "soft" });
        }

        // 配重：loads＝轉移量、grip＝再加總抓地力、battery＝電池擺放決定重心
        const onLoads = is("loads", "grip", "battery");
        cols.forEach(c => show(c.holder, onLoads));
        show(cg, onLoads);
        state.batWant.copy(batteryBase);
        if (onLoads) {
          let front = (p.front ?? 47) / 100, h = (p.cgh ?? 280) / 1000, g = p.g ?? 1.2;
          if (is("battery")) {
            const bh = p.bh ?? 30, bpos = p.bpos ?? 0;
            ({ front, h } = batteryCg(bh, bpos));
            g = 1.2;
            state.batWant.set(batteryBase.x, batteryBase.y + (bh - 30) / 100 * 2, batteryBase.z - bpos / 100 * 1.2);
          }
          const loads = cornerLoads(front, h, g);
          cols.forEach((c, i) => {
            const hgt = Math.max(0.04, loads[i] / 140 * 1.6);
            c.col.scale.y = hgt; c.col.position.y = hgt / 2;
            labels.push({ at: [c.holder.position.x, hgt + 0.35, c.z], text: loads[i] < 0.5 ? "離地 0 kg" : `${Math.round(loads[i])} kg`, tone: loads[i] < 5 ? "accent" : "ink" });
          });
          cg.position.set(0, 0.3 + h * 2.25, zf + (1 - front) * L);
          labels.push({ at: [0, cg.position.y + 0.5, cg.position.z], text: "重心", tone: "accent" });
          if (g > 0) labels.push({ at: [0, 0.3, zf - 1.9], text: "右彎：重量往左邊搬", tone: "soft" });
          if (is("loads")) labels.push({ at: [0, 2.4, -0.3], text: `轉移 ΔW ≈ ${Math.round(M * g * h / TRACK)} kg`, tone: "accent" });
          if (is("grip", "battery")) {
            const sum = (ls) => ls.reduce((a, kg) => a + gripOf(kg), 0);
            const ratio = sum(loads) / sum(cornerLoads(front, h, 0));
            labels.push({ at: [0, 2.4, -0.3], text: `四輪總抓地力 ${(ratio * 100).toFixed(1)}%`, tone: "accent" });
          }
          if (is("battery")) labels.push({ at: [0, 2.0, zr + 0.6], text: `重心高 ${Math.round(h * 1000)} mm　前軸 ${Math.round(front * 100)}%`, tone: "ink" });
        }

        // 端板：講翼片怎麼產生下壓力／阻力時淡化，露出翼型剖面
        state.plateWant = is("foil", "downforce", "drag") ? 0.15 : 1;

        // 下壓力：F = ½ρV²·(S·CL)，S·CL 取 3.0 m²，前四後六
        // 阻力：D = ½ρV²·(A·CD)，A = 1.0 m²、CD = 1.2（A·CD = 1.2 m² = 3.0 ÷ 升阻比 2.5）
        // 箭頭長度＝forceLen(力)，三支同一個比例
        const onAero = is("downforce"), onDrag = is("drag"), onFoil = is("foil");
        show(dfFront, onAero); show(dfRear, onAero || onFoil); show(drag, onAero || onDrag);
        show(dragArea, onDrag); show(air, onFoil);
        if (onAero || onDrag || onFoil) {
          const v = (onFoil ? 80 : p.speed ?? shot.speed ?? 60) / 3.6, q = 0.5 * 1.225 * v * v;
          const total = q * 3.0, f = total * 0.4, r = total * 0.6, d = q * 1.0 * 1.2;
          dfFront.set(P3(0, 0.42 + forceLen(f), -2.55), P3(0, 0.42, -2.55));
          dfRear.set(P3(0, 2.2 + forceLen(r), rwZ + 0.1), P3(0, 2.2, rwZ + 0.1));
          drag.set(P3(0, 1.05, DRAG_Z), P3(0, 1.05, DRAG_Z + forceLen(d)));
          if (onAero) labels.push({ at: [0, 0.6 + forceLen(f), -2.55], text: `前翼 ${Math.round(f)} N`, tone: "blue" },
                                  { at: [0, 2.4 + forceLen(r), rwZ + 0.1], text: `尾翼 ${Math.round(r)} N`, tone: "blue" });
          if (onAero || onDrag) labels.push({ at: [0, 1.35, DRAG_Z + forceLen(d) + 0.2], text: `阻力 ${Math.round(d)} N`, tone: onDrag ? "accent" : "soft" });
          if (onDrag) labels.push({ at: [0, 2.5, DRAG_Z], text: "迎風面積 A（示意 1.0 m²）", tone: "accent" });
          if (onFoil) {
            air.set(P3(0, rwY - 0.32, rwZ - 1.1), P3(0, rwY - 0.32, rwZ + 1.25));
            labels.push({ at: [0, 2.4 + forceLen(r), rwZ + 0.1], text: "下壓力", tone: "blue" },
                        { at: [0, rwY + 0.85, rwZ - 0.3], text: "上面：壓力較高", tone: "ink" },
                        { at: [0, rwY - 0.55, rwZ - 0.6], text: "下面：氣流快、壓力低", tone: "soft" });
          }
        }

        // 煞車發熱：½mv²，前 65％、後 35％
        state.heatWant = is("brakeheat") ? Math.min(1, (p.speed ?? shot.speed ?? 80) / 110) : 0;
        if (is("brakeheat")) {
          const v = (p.speed ?? shot.speed ?? 80) / 3.6, kj = 0.5 * M * v * v / 1000;
          labels.push({ at: [hx - 0.42, WR + 0.95, zf], text: `前輪吸收 ${Math.round(kj * 0.65)} kJ`, tone: "accent" },
                      { at: [hx - 0.42, WR + 0.95, zr], text: `後輪 ${Math.round(kj * 0.35)} kJ`, tone: "soft" });
        }
        if (is("energy")) labels.push({ at: [0, 1.25, 0.85], text: "約 5–7 kWh", tone: "soft" });

        // 胎溫：一進來四顆都是冷的（藍），跑起來慢慢變熱；左右彎輪流，外側輪比較熱
        const temp = is("tiretemp");
        if (temp && !state.temp) { state.tempT = 0; tires.forEach(t => { t.temp = 40; }); }
        state.temp = temp;
        if (temp) {
          for (const t of tires) labels.push({ at: [t.x + Math.sign(t.x) * 1.0, WR, t.z], text: `${Math.round(t.temp)}°C`, tone: "ink" });
          const turn = state.ay > 0.25 ? "左彎：右側是外側" : state.ay < -0.25 ? "右彎：左側是外側" : "直線";
          labels.push({ at: [0, 0.6, zf - 1.7], text: turn, tone: "soft" },
                      { at: [0, 0.3, zr + 1.6], text: "藍＝太冷　綠＝剛好　黃紅＝太熱", tone: "soft" });
        }
        return labels;
      },
      tick(dt) {
        let relabel = false;
        if (state.cycle && !reduceMotion) {
          state.cycleT += dt;
          if (state.cycleT > 1.8) {
            state.cycleT = 0; state.cycleI = (state.cycleI + 1) % CYCLE.length;
            state.focus = CYCLE[state.cycleI]; relabel = true;
          }
        }
        // 胎溫：9 秒一圈（直線 → 左彎 → 直線 → 右彎）。熱胎時整體往 78°C 走，彎道外側再多 30°C
        if (state.temp) {
          state.tempT += reduceMotion ? 0 : dt;
          const ph = (state.tempT % 9) / 9;
          const bend = (a, b) => ph > a && ph < b ? Math.sin((ph - a) / (b - a) * Math.PI) : 0;
          state.ay = bend(0.12, 0.45) - bend(0.6, 0.93);              // 正＝左彎
          const warm = Math.min(1, state.tempT / 7);                    // 頭幾秒是冷胎
          for (const t of tires) {
            const outer = Math.max(0, Math.sign(t.x) * state.ay);       // 左彎時右側（x > 0）是外側
            const target = 40 + warm * 38 + outer * 30 * warm + Math.abs(state.ay) * 4;
            t.temp += (target - t.temp) * (1 - Math.pow(0.45, dt));
          }
          state.tempLabel += dt;
          if (state.tempLabel > 0.25) { state.tempLabel = 0; relabel = true; }
          state.steerWant = state.ay * 0.32;                  // 左彎（ay > 0）→ 前輪往左（正角）
          state.flowWant = 3.0 - 1.2 * Math.abs(state.ay);   // 過彎慢一點
        }
        // 前輪轉向（內側輪轉多一點：簡化的阿克曼）、輪子滾動、地面短線往車尾流
        state.steer += (state.steerWant - state.steer) * (reduceMotion ? 1 : 1 - Math.pow(0.01, dt));
        state.flowV += (state.flowWant - state.flowV) * (reduceMotion ? 1 : 1 - Math.pow(0.15, dt));
        if (!reduceMotion) {
          state.flowZ = (state.flowZ + state.flowV * dt) % FLOW_SPAN;
          state.roll = (state.roll - state.flowV / WR * dt) % (Math.PI * 2);   // 車往 −z 跑：輪頂往 −z 轉
        }
        for (const wh of wheels) {
          wh.w.rotation.x = state.roll;
          if (wh.front) {
            const inner = Math.sign(wh.x) === -Math.sign(state.steer);
            wh.pivot.rotation.y = state.steer * (inner ? 1.12 : 0.9);
          }
        }
        if (flow.visible) for (const { d, base } of dashes) {
          const z = ((base + state.flowZ) % FLOW_SPAN) - FLOW_SPAN / 2;
          const e = Math.max(0.001, Math.min(1, (FLOW_SPAN / 2 - Math.abs(z)) / 1.5));
          d.position.z = z; d.scale.set(e, 1, e);
        }
        // 電池擺放示範：電池平滑移到新位置
        state.bat.lerp(state.batWant, reduceMotion ? 1 : 1 - Math.pow(0.01, dt));
        battery.position.copy(state.bat);
        state.plate += (state.plateWant - state.plate) * (reduceMotion ? 1 : 1 - Math.pow(0.02, dt));
        const k = 1 - Math.pow(0.002, dt);
        state.heat += (state.heatWant - state.heat) * (1 - Math.pow(0.15, dt));
        const accent = mat.accent.color;
        body.traverse(o => {
          if (!o.isMesh) return;
          const target = !state.focus ? 0 : o.userData.sub === state.focus ? 1 : -1;
          o.userData.mix += (target - o.userData.mix) * k;
          const m = o.userData.mix;
          o.material.color.copy(o.userData.base.color).lerp(accent, Math.max(0, m) * 0.85);
          o.material.emissive.copy(accent).multiplyScalar(Math.max(0, m) * 0.12);
          if (o.userData.disc) {
            o.material.emissive.setRGB(1, 0.3, 0.05).multiplyScalar(state.heat * (o.userData.disc === "front" ? 1.7 : 0.9));
          }
          o.material.opacity = (m < 0 ? 1 + m * 0.85 : 1) * (o.userData.endplate ? state.plate : 1);
          o.material.depthWrite = o.material.opacity > 0.5;
        });
        if (state.temp) for (const t of tires) {
          tempColor(t.temp, t.mesh.material.color);
          t.mesh.material.emissive.copy(t.mesh.material.color).multiplyScalar(0.25);
          t.mesh.material.opacity = 1; t.mesh.material.depthWrite = true;
        }
        return relabel ? "relabel" : undefined;
      },
    };
  }

  // ── 平台與路線 ──
  const builders = { start: startExhibit, wheel: wheelExhibit, chassis: chassisExhibit, steering: steeringExhibit, suspension: suspensionExhibit, drivetrain: drivetrainExhibit, car: formulaExhibit };
  const places = {};
  const gates = [];
  ACADEMY_PLACES.forEach((def, i) => {
    const center = V(def.pos);
    const disc = new THREE.Mesh(new THREE.CylinderGeometry(def.r, def.r * 0.96, 0.5, 96), mat.platform);
    disc.position.copy(center).y -= 0.25;
    disc.receiveShadow = true;
    scene.add(disc);
    const exhibit = (builders[def.exhibit] || (() => ghostExhibit(def.r)))();
    exhibit.group.position.copy(center);
    scene.add(exhibit.group);
    places[def.id] = { ...def, kind: def.exhibit, index: i, center, exhibit };
    // 路線從平台靠中線的那一側經過
    const toward = Math.abs(center.x) < 3 ? 0 : -Math.sign(center.x);
    gates.push(new THREE.Vector3(center.x + toward * def.r, center.y + 0.04, center.z + (toward ? 0 : def.r * 0.0)));
  });
  const curve = new THREE.CatmullRomCurve3(gates, false, "catmullrom", 0.5);
  const route = new THREE.Mesh(new THREE.TubeGeometry(curve, 400, 0.07, 10, false), mat.route);
  scene.add(route);

  // ── 標籤（HTML，投影到畫面上） ──
  const partLabels = [];   // 目前視角的零件標籤
  let partLabelDefs = [];
  function setPartLabels(defs, place) {
    partLabelDefs = defs.map(d => ({ ...d, world: V(d.at).add(place.center) }));
    while (partLabels.length < partLabelDefs.length) {
      const el = document.createElement("div");
      el.className = "aw-label";
      labelLayer.appendChild(el);
      partLabels.push(el);
    }
    partLabels.forEach((el, i) => {
      const d = partLabelDefs[i];
      el.textContent = d ? d.text : "";
      el.dataset.tone = d ? d.tone || "ink" : "";
      el.classList.toggle("is-on", !!d);
    });
  }
  const placeLabels = {};
  function setPlaceLabels(items) {   // items: [{ place, no, title, planned }]
    Object.values(placeLabels).forEach(l => l.el.remove());
    for (const k of Object.keys(placeLabels)) delete placeLabels[k];
    for (const it of items) {
      const el = document.createElement("button");
      el.type = "button";
      el.className = `aw-place${it.planned ? " is-planned" : ""}`;
      el.innerHTML = `<span class="aw-place-no"></span><span class="aw-place-title"></span>`;
      el.children[0].textContent = it.no;
      el.children[1].textContent = it.title;
      el.addEventListener("click", () => onPickPlace?.(it.place));
      labelLayer.appendChild(el);
      const p = places[it.place];
      placeLabels[it.place] = { el, world: p.center.clone().add(new THREE.Vector3(0, p.kind === "ghost" || p.kind === "start" ? 1.3 : 4.8, 0)) };
    }
  }

  // ── 鏡頭 ──
  const goal = { pos: new THREE.Vector3(), look: new THREE.Vector3(), fx: 0, fy: 0, fogFar: 120 };
  const cur  = { pos: new THREE.Vector3(), look: new THREE.Vector3(), fx: 0, fy: 0, fogFar: 120 };
  const orbit = { yaw: 0, pitch: 0, wantYaw: 0, wantPitch: 0 };
  let current = { place: places.start, shot: places.start.exhibit.shots.hero, params: {}, reveal: false };
  let overview = false, snap = true, distScale = 1, framing = { x: 0, y: 0 };

  // 鏡頭轉場：固定時間、慢進慢出。看的點直線移過去，鏡頭繞著它轉（不會從展品中間穿過）。
  // 轉場時間看要轉的角度和移動距離決定（0.9～3.2 秒）；進出總覽 2.4 秒。
  const tw = {
    t: 1, dur: 1, key: null,
    fromLook: new THREE.Vector3(), fromOff: new THREE.Vector3(), fromFx: 0, fromFy: 0, fromFog: 120,
    toLook: new THREE.Vector3(), toOff: new THREE.Vector3(), toFx: 0, toFy: 0, toFog: 120,
  };
  tw.fromSph = { r: 0, yaw: 0, pitch: 0 }; tw.toSph = { r: 0, yaw: 0, pitch: 0 };
  const easeInOut = (x) => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
  const easeOut = (x) => 1 - Math.pow(1 - x, 3);
  function startTween() {
    const off = goal.pos.clone().sub(goal.look);
    const same = tw.toLook.distanceToSquared(goal.look) < 1e-6 && tw.toOff.distanceToSquared(off) < 1e-6
      && Math.abs(tw.toFx - goal.fx) < 1e-4 && Math.abs(tw.toFy - goal.fy) < 1e-4;
    if (same && !snap) return;                       // 目標沒變（例如只是拉滑桿），不要重來
    const key = overview ? "__overview" : current.place.id;
    const interrupted = tw.t < 1;
    tw.fromLook.copy(cur.look); tw.fromOff.copy(cur.pos).sub(cur.look);
    tw.fromFx = cur.fx; tw.fromFy = cur.fy; tw.fromFog = cur.fogFar;
    tw.toLook.copy(goal.look); tw.toOff.copy(off);
    tw.toFx = goal.fx; tw.toFy = goal.fy; tw.toFog = goal.fogFar;
    // 鏡頭位置拆成「水平方位角／仰角／距離」三個量分開內插：
    // 只會水平繞圈＋抬頭低頭，不會翻過頭頂或鑽到地板下（四元數在差 180° 時會亂選軸）
    toSph(tw.fromOff, tw.fromSph); toSph(tw.toOff, tw.toSph);
    let dYaw = tw.toSph.yaw - tw.fromSph.yaw;
    dYaw = Math.atan2(Math.sin(dYaw), Math.cos(dYaw));             // 走短的那一邊
    tw.toSph.yaw = tw.fromSph.yaw + dYaw;
    const turn = Math.abs(dYaw) * Math.cos((tw.fromSph.pitch + tw.toSph.pitch) / 2)  // 俯視時方位角幾乎看不出來
               + Math.abs(tw.toSph.pitch - tw.fromSph.pitch);
    const travel = tw.fromLook.distanceTo(tw.toLook);
    const changePlace = key !== tw.key && tw.key !== null;
    const toOverview = key === "__overview" || tw.key === "__overview";
    // 時間跟著「要轉多少、要走多遠」走：小調整很快，大轉向慢慢轉，不會一秒甩半圈
    tw.dur = toOverview ? 2.4
      : Math.min(3.2, Math.max(changePlace ? 2.0 : 0.9, 0.8 + turn * 0.75 + Math.sqrt(travel) * 0.22));
    // 某些視角要轉很大的角度：shot.dur 指定進出這個視角最少幾秒（同一站裡才算，換站照原本的）
    const slow = Math.max(overview ? 0 : current.shot?.dur || 0, tw.shotDur || 0);
    if (!toOverview && !changePlace && slow) tw.dur = Math.max(tw.dur, slow);
    tw.shotDur = overview ? 0 : current.shot?.dur || 0;
    // 換站或大轉向時半路稍微拉遠：看得到前後兩座平台／整台車，不會擦過展品
    tw.bump = toOverview ? 0 : (changePlace ? 0.4 : 0) + Math.min(0.35, turn * 0.12);
    tw.key = key;
    tw.ease = interrupted ? easeOut : easeInOut;     // 半路被打斷：從目前速度接著走，不要先停下來
    tw.t = snap || reduceMotion ? 1 : 0;
  }
  function toSph(v, out) {
    out.r = v.length();
    out.yaw = Math.atan2(v.x, v.z);
    out.pitch = out.r > 1e-6 ? Math.asin(Math.max(-1, Math.min(1, v.y / out.r))) : 0;
    return out;
  }
  function stepTween(dt) {
    if (tw.t < 1) tw.t = Math.min(1, tw.t + dt / tw.dur);
    const e = tw.t >= 1 ? 1 : tw.ease(tw.t);
    cur.look.lerpVectors(tw.fromLook, tw.toLook, e);
    if (e >= 1 || tw.fromSph.r < 1e-6 || tw.toSph.r < 1e-6) {
      cur.pos.copy(cur.look).add(tw.toOff);
    } else {
      const a = tw.fromSph, b = tw.toSph;
      const yaw = a.yaw + (b.yaw - a.yaw) * e;
      const pitch = a.pitch + (b.pitch - a.pitch) * e;
      const len = (a.r + (b.r - a.r) * e) * (1 + (tw.bump || 0) * Math.sin(Math.PI * e));
      const c = Math.cos(pitch);
      cur.pos.set(Math.sin(yaw) * c, Math.sin(pitch), Math.cos(yaw) * c).multiplyScalar(len).add(cur.look);
    }
    cur.fx = tw.fromFx + (tw.toFx - tw.fromFx) * e;
    cur.fy = tw.fromFy + (tw.toFy - tw.fromFy) * e;
    cur.fogFar = tw.fromFog + (tw.toFog - tw.fromFog) * e;
  }

  function retarget() {
    const { place, shot } = current;
    if (overview) {
      // 整條路線的俯視：從右上方往下看，路線在畫面上由左往右排開
      goal.look.set(0, -7, -64); goal.pos.set(74, 132, -64);
      goal.fx = 0; goal.fy = 0.1; goal.fogFar = 420;
    } else {
      const look = V(shot.look);
      const off = V(shot.pos).sub(look).multiplyScalar(distScale);
      goal.look.copy(look).add(place.center);
      goal.pos.copy(goal.look).add(off);
      goal.fx = framing.x; goal.fy = framing.y; goal.fogFar = 120;
    }
    startTween();
    sun.target.position.copy(place.center);
    sun.position.copy(place.center).add(new THREE.Vector3(7, 16, 9));
  }
  function applyExhibit() {
    const { place, shot, params, reveal } = current;
    setPartLabels(overview ? [] : place.exhibit.apply(shot, params, reveal), place);
  }

  const resize = () => {
    const w = canvas.clientWidth, h = canvas.clientHeight;
    if (!w || !h) return;
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
  };
  resize();
  const ro = new ResizeObserver(resize);
  ro.observe(canvas);

  // 拖曳：暫時繞著展品看；換視角時自動回正
  let drag = null;
  const onDown = (e) => { drag = { x: e.clientX, y: e.clientY }; canvas.setPointerCapture(e.pointerId); };
  const onMove = (e) => {
    if (!drag || overview) return;
    orbit.wantYaw -= (e.clientX - drag.x) * 0.006;
    orbit.wantPitch = Math.max(-0.35, Math.min(0.5, orbit.wantPitch + (e.clientY - drag.y) * 0.004));
    drag = { x: e.clientX, y: e.clientY };
  };
  const onUp = () => { drag = null; };
  canvas.addEventListener("pointerdown", onDown);
  canvas.addEventListener("pointermove", onMove);
  canvas.addEventListener("pointerup", onUp);
  canvas.addEventListener("pointercancel", onUp);

  const clock = new THREE.Clock();
  const tmp = new THREE.Vector3(), offset = new THREE.Vector3(), right = new THREE.Vector3();
  let raf = 0;
  const tick = () => {
    raf = requestAnimationFrame(tick);
    const dt = Math.min(clock.getDelta(), 0.05);
    const t = clock.elapsedTime;
    snap = false;
    stepTween(dt);
    scene.fog.far = cur.fogFar; scene.fog.near = cur.fogFar * 0.22;
    orbit.yaw += (orbit.wantYaw - orbit.yaw) * (1 - Math.pow(0.002, dt));
    orbit.pitch += (orbit.wantPitch - orbit.pitch) * (1 - Math.pow(0.002, dt));

    // 鏡頭位置＝目標點＋（視線向量轉一點角度：只有拖曳，沒有自動晃動）
    offset.copy(cur.pos).sub(cur.look);
    offset.applyAxisAngle(UP, orbit.yaw);
    right.crossVectors(offset, UP).normalize();
    if (right.lengthSq() > 0.5) offset.applyAxisAngle(right, -orbit.pitch);
    camera.position.copy(cur.look).add(offset);
    camera.lookAt(cur.look);
    const w = canvas.clientWidth, h = canvas.clientHeight;
    if (w && h) camera.setViewOffset(w, h, cur.fx * w, cur.fy * h, w, h);

    const fk = 1 - Math.pow(0.0008, dt);
    for (const o of fx) {
      o.userData.s += (o.userData.want - o.userData.s) * (reduceMotion ? 1 : fk);
      o.visible = o.userData.s > 0.02;
      if (o.visible && !o.userData.keepScale) o.scale.setScalar(o.userData.s);
    }
    for (const p of Object.values(places)) {
      if (p.exhibit.tick?.(dt) === "relabel" && p === current.place) applyExhibit();
    }
    renderer.render(scene, camera);

    // 標籤投影
    const place = (el, world, lift) => {
      tmp.copy(world).project(camera);
      const visible = tmp.z < 1 && Math.abs(tmp.x) < 1.15 && Math.abs(tmp.y) < 1.15;
      el.style.transform = `translate(${(tmp.x + 1) / 2 * w}px, ${(1 - tmp.y) / 2 * h}px) translate(-50%, ${lift})`;
      return visible;
    };
    partLabels.forEach((el, i) => { const d = partLabelDefs[i]; if (d) place(el, d.world, "-50%"); });
    for (const [id, l] of Object.entries(placeLabels)) {
      const visible = place(l.el, l.world, "-100%");
      const dist = camera.position.distanceTo(l.world);
      const here = !overview && (id === current.place.id || current.place.id !== "start");
      const fade = overview ? 1 : Math.max(0, Math.min(1, (cur.fogFar * 0.8 - dist) / 30));
      l.el.style.opacity = visible && !here ? fade : 0;
      l.el.style.pointerEvents = visible && !here && fade > 0.3 ? "auto" : "none";
    }
  };
  retarget(); applyExhibit();
  raf = requestAnimationFrame(tick);

  return {
    places,
    // 走到某個平台的某個視角。
    go(placeId, shotDef, { params = {}, reveal = false } = {}) {
      const place = places[placeId] || places.start;
      const ex = place.exhibit;
      const named = ex.shots[shotDef?.view] || ex.shots.hero;
      const shot = { ...named, ...shotDef };
      const moved = current.place !== place || current.shot.pos !== shot.pos;
      current = { place, shot, params, reveal };
      if (moved) { orbit.wantYaw = 0; orbit.wantPitch = 0; }
      retarget(); applyExhibit();
    },
    setParams(params) { current.params = params; applyExhibit(); },
    setReveal(reveal) { current.reveal = reveal; applyExhibit(); },
    setOverview(on) { overview = on; orbit.wantYaw = 0; orbit.wantPitch = 0; retarget(); applyExhibit(); },
    // 文字欄佔掉一部分畫面時，把展品往旁邊讓；窄螢幕把鏡頭拉遠一點
    setFraming(x, y, scale = 1) { framing = { x, y }; distScale = scale; retarget(); },
    setPlaceLabels,
    dispose() {
      cancelAnimationFrame(raf);
      ro.disconnect();
      themeWatch.disconnect();
      canvas.removeEventListener("pointerdown", onDown);
      canvas.removeEventListener("pointermove", onMove);
      canvas.removeEventListener("pointerup", onUp);
      canvas.removeEventListener("pointercancel", onUp);
      Object.values(places).forEach(p => p.exhibit.dispose?.());
      labelLayer.replaceChildren();
      envTex.dispose();
      renderer.dispose();
    },
  };
}

Object.assign(window, { createAcademyWorld, ACADEMY_PLACES });
