/**
 * S-24 · 底部下栏抽屉 · 状态机与几何纯函数测试（Node，无浏览器 / 无 three / 无 DOM）。
 * -----------------------------------------------------------------------------
 * 覆盖（按契约 §1 定稿参数 + §3 导出契约）：
 *   ① 常量逐字核对（契约 §3）
 *   ② 三档高度：peek 恒 60px；half = round(屏高×0.45)；full = round(屏高×0.88)（4 屏宽 × 4 屏高）
 *   ③ tab 五等分：等宽 / 不重叠 / 总宽 = W−24−32 / 末格右缘 ≤ W−12 / 320 不溢出
 *   ④ peek 档：tab 行完全移出屏幕（tabVisible=false、tabRow.y ≥ screenH、content 高度 ≤ 0）
 *   ⑤ tab 字号：390→13、320→12、414/430→13
 *   ⑥ 拖拽跟手：drawerDragTo 后 height 严格等于传入值（不夹取到档位）
 *   ⑦ 松手吸附：half 附近 ±5px → half；full 附近 → full；full 拖到 80px → peek
 *   ⑧ 点把手：peek→half；half→peek；full→full（不动）
 *   ⑨ 动画 380ms：t=0 → from；t=190ms → 中点；t≥380ms → to；drawerEasing 单调、两端 0/1、中点 0.5
 *   ⑩ drawerFraming 三档精确值（zoom / dyFrac / scale）
 *   ⑪ 纯函数：不改入参、返回新对象、数值全有限（无 NaN）
 *
 * 运行：
 *   node tests/drawer-state.test.ts
 *   （或，与 tests/ 其它测试同法：npx esbuild tests/drawer-state.test.ts --bundle --platform=node
 *     --format=esm --outfile=/tmp/s24-drawer-state.test.mjs && node /tmp/s24-drawer-state.test.mjs）
 * 结果 JSON（可选）：node tests/drawer-state.test.ts /tmp/s24-drawer-state.json
 */
import { writeFileSync } from 'node:fs';
import {
  DRAWER_PEEK_PX, DRAWER_HALF_FRAC, DRAWER_FULL_FRAC, DRAWER_ANIM_MS, DRAWER_COIN_MOVE_MS,
  DRAWER_TAB_COUNT, DRAWER_TAB_PAD, DRAWER_TAB_GAP, DRAWER_TAB_RADIUS, DRAWER_TAB_BORDER,
  DRAWER_TAB_BORDER_COLOR, DRAWER_TAB_SELECT_BG, DRAWER_TAB_SELECT_BORDER, DRAWER_TAB_ROW_H, DRAWER_CLICK_SLOP,
  DRAWER_TABS, DRAWER_ISLAND_DY, DRAWER_CAM_ZOOM, DRAWER_ISLAND_SCALE,
  drawerFraming, drawerHeightFor, drawerStageForHeight, drawerTabFontSize, drawerTabCells, layoutDrawer,
  createDrawerState, drawerBeginDrag, drawerDragTo, drawerEndDrag, drawerSetStage, drawerTapHandle,
  drawerTick, drawerIsAnimating, drawerEasing,
  type DrawerStage, type DrawerTabId, type DrawerState
} from '../src/ui/drawer.ts';

let checks = 0;
const fails: string[] = [];
const ok = (cond: boolean, msg: string): void => { checks++; if (!cond) { fails.push(msg); } };
const near = (a: number, b: number, tol = 1e-9): boolean => Math.abs(a - b) <= tol;

const WIDTHS = [320, 390, 414, 430];
const HEIGHTS = [568, 844, 896, 932];
const STAGES: DrawerStage[] = ['peek', 'half', 'full'];

/* ================================================================ ① 常量 */
{
  ok(DRAWER_PEEK_PX === 60, '① peek = 60px');
  ok(DRAWER_HALF_FRAC === 0.45, '① half = 45% 屏高');
  ok(DRAWER_FULL_FRAC === 0.88, '① full = 88% 屏高');
  ok(DRAWER_ANIM_MS === 380, '① 抽屉动画 = 380ms');
  ok(DRAWER_COIN_MOVE_MS === 220, '① 金币胶囊位移 = 220ms');
  ok(DRAWER_TAB_COUNT === 5, '① tab 数 = 5');
  ok(DRAWER_TAB_PAD === 12, '① tab 左右 padding = 12');
  ok(DRAWER_TAB_GAP === 8, '① tab 格间 gap = 8');
  ok(DRAWER_TAB_RADIUS === 9, '① tab 圆角 = 9');
  ok(DRAWER_TAB_BORDER === 1, '① tab 描边 = 1px');
  ok(DRAWER_TAB_BORDER_COLOR === '#D8C7A4', '① tab 描边色 = #D8C7A4');
  ok(DRAWER_TAB_SELECT_BG === 'rgba(247,197,92,0.18)', '① 选中底 = 淡金 18%');
  ok(DRAWER_TAB_SELECT_BORDER === '#C99A3F', '① 选中描边 = #C99A3F');
  ok(DRAWER_TAB_ROW_H === 34, '① tab 行高 = 34px');
  ok(DRAWER_CLICK_SLOP === 6, '① 点击判定阈值 = 6px');
  ok(DRAWER_TABS.length === 5, '① DRAWER_TABS 5 项');
  ok(
    DRAWER_TABS.map((t) => t.id).join(',') === 'build,land,resident,block,more',
    `① DRAWER_TABS 顺序 = build,land,resident,block,more（实得 ${DRAWER_TABS.map((t) => t.id).join(',')}）`
  );
  ok(
    DRAWER_TABS.map((t) => t.label).join(',') === '建筑,土地,居民,街区,其他',
    `① DRAWER_TABS 文案 = 建筑,土地,居民,街区,其他（实得 ${DRAWER_TABS.map((t) => t.label).join(',')}）`
  );
}

/* ================================================================ ② 三档高度 */
{
  for (const w of WIDTHS) {
    for (const h of HEIGHTS) {
      ok(drawerHeightFor('peek', h) === 60, `② ${w}×${h} peek 恒 60px（实得 ${drawerHeightFor('peek', h)}）`);
      ok(drawerHeightFor('half', h) === Math.round(h * 0.45), `② ${w}×${h} half = round(H×0.45) = ${Math.round(h * 0.45)}`);
      ok(drawerHeightFor('full', h) === Math.round(h * 0.88), `② ${w}×${h} full = round(H×0.88) = ${Math.round(h * 0.88)}`);
      // 档位高度严格递增
      ok(drawerHeightFor('peek', h) < drawerHeightFor('half', h), `② ${w}×${h} peek < half`);
      ok(drawerHeightFor('half', h) < drawerHeightFor('full', h), `② ${w}×${h} half < full`);
      // 吸附：正好落在档位高度上 → 该档
      for (const st of STAGES) {
        ok(drawerStageForHeight(drawerHeightFor(st, h), h) === st, `② ${w}×${h} 高度 ${drawerHeightFor(st, h)} 吸附回 ${st}`);
      }
    }
  }
  // 关键数字抽查（契约/说明.md 的 390×844）
  ok(drawerHeightFor('half', 844) === 380, `② 390×844 half 实测 ${drawerHeightFor('half', 844)}（契约未取整值 379.8 → 取整 380）`);
  ok(drawerHeightFor('full', 844) === 743, `② 390×844 full 实测 ${drawerHeightFor('full', 844)}（原型 742.72 → 取整 743）`);
  ok(drawerHeightFor('peek', 844) === 60, '② 390×844 peek 实测 60');
}

/* ================================================================ ③ tab 五等分 */
{
  for (const w of WIDTHS) {
    const cells = drawerTabCells(w);
    ok(cells.length === DRAWER_TAB_COUNT, `③ W=${w} 共 5 格（实得 ${cells.length}）`);
    const cellW = cells[0].w;
    ok(near(cellW, (w - 24 - 32) / 5, 1e-12), `③ W=${w} 每格宽 = (W−24−32)/5 = ${(w - 24 - 32) / 5}（实得 ${cellW}）`);
    let same = true, overlap = false, sum = 0;
    for (let i = 0; i < cells.length; i++) {
      sum += cells[i].w;
      if (!near(cells[i].w, cellW, 1e-12)) { same = false; }
      if (i > 0 && cells[i].x < cells[i - 1].x + cells[i - 1].w - 1e-12) { overlap = true; }
    }
    ok(same, `③ W=${w} 5 格等宽`);
    ok(!overlap, `③ W=${w} 5 格互不重叠`);
    ok(near(sum, w - 24 - 32, 1e-9), `③ W=${w} 总宽 = W−24−32 = ${w - 56}（实得 ${sum}）`);
    const last = cells[cells.length - 1];
    ok(last.x + last.w <= w - 12 + 1e-9, `③ W=${w} 末格右缘 ${last.x + last.w} ≤ W−12 = ${w - 12}`);
    ok(cells[0].x >= 0 && last.x + last.w <= w, `③ W=${w} 整排不越出屏幕（0 … ${last.x + last.w}）`);
    // gap = 8
    ok(near(cells[1].x - (cells[0].x + cells[0].w), 8, 1e-9), `③ W=${w} 格间 gap = 8（实得 ${cells[1].x - (cells[0].x + cells[0].w)}）`);
  }
  // 关键数字抽查：320 每格 52.8px
  const c320 = drawerTabCells(320);
  ok(near(c320[0].w, 52.8, 1e-9), `③ 320 宽每格 tab 宽度实测 ${c320[0].w}px（契约值 52.8px）`);
  ok(near(c320[4].x + c320[4].w, 308, 1e-9), `③ 320 宽末格右缘实测 ${c320[4].x + c320[4].w}px（= W−12 = 308）`);
  const c390 = drawerTabCells(390);
  ok(near(c390[0].w, 66.8, 1e-9), `③ 390 宽每格 tab 宽度实测 ${c390[0].w}px（说明.md 实测 66.8px）`);
}

/* ================================================================ ④⑤ layoutDrawer：peek 移出屏幕 + 字号 */
{
  for (const w of WIDTHS) {
    for (const h of HEIGHTS) {
      const peekH = drawerHeightFor('peek', h);
      const L = layoutDrawer({ screenW: w, screenH: h, stage: 'peek', height: peekH, tab: 'build', activeTab: 'build' });
      ok(L.tabVisible === false, `④ ${w}×${h} peek 时 tabVisible = false（实得 ${L.tabVisible}）`);
      ok(L.tabRow.y >= h, `④ ${w}×${h} peek 时 tabRow.y ${L.tabRow.y} ≥ screenH ${h}（完全移出屏幕）`);
      ok(L.content.h <= 0, `④ ${w}×${h} peek 时 content 高度 ${L.content.h} ≤ 0`);
      ok(L.content.y + L.content.h <= h, `④ ${w}×${h} peek 时内容区不越过屏幕底边（底 ${L.content.y + L.content.h} ≤ ${h}）`);
      ok(L.content.y >= L.tabRow.y + L.tabRow.h, `④ ${w}×${h} peek 时内容区上沿仍在 tab 行之下（${L.content.y} ≥ ${L.tabRow.y + L.tabRow.h}）`);
      // 面板几何
      ok(L.panel.y === h - peekH && L.panel.h === peekH && L.panel.w === w && L.panel.x === 0, `④ ${w}×${h} panel 贴底且 x=0/w=屏宽`);
      ok(L.handle.y === L.panel.y && L.handle.h === 60, `④ ${w}×${h} handle = 面板顶部一条 60px`);
      ok(L.tabRow.y === L.handle.y + L.handle.h, `④ ${w}×${h} tabRow 贴在 handle 下方`);
      ok(L.tabCells.length === 5, `④ ${w}×${h} layoutDrawer 给 5 个 tabCells`);
      for (const c of L.tabCells) { ok(c.y === L.tabRow.y && c.h === DRAWER_TAB_ROW_H, `④ ${w}×${h} tabCell 行位置/行高正确`); }
      // 字号
      const expectFont = w <= 330 ? 12 : 13;
      ok(L.tabFont === expectFont, `⑤ ${w} 宽 tab 字号 = ${expectFont}（实得 ${L.tabFont}）`);
      ok(drawerTabFontSize(390) === 13, '⑤ 390 → 13px');
      ok(drawerTabFontSize(320) === 12, '⑤ 320 → 12px');
      ok(drawerTabFontSize(414) === 13, '⑤ 414 → 13px');
      ok(drawerTabFontSize(430) === 13, '⑤ 430 → 13px');

      // half / full：tab 行在屏内可见
      for (const st of ['half', 'full'] as DrawerStage[]) {
        const hh = drawerHeightFor(st, h);
        const L2 = layoutDrawer({ screenW: w, screenH: h, stage: st, height: hh, tab: 'land', activeTab: 'land' });
        ok(L2.tabVisible === true, `④ ${w}×${h} ${st} 档 tab 行可见`);
        ok(L2.content.h > 0, `④ ${w}×${h} ${st} 档 content 高度 ${L2.content.h} > 0`);
        ok(L2.content.y > L2.tabRow.y + L2.tabRow.h, `④ ${w}×${h} ${st} 档 content 在 tab 行下方`);
        ok(L2.content.y + L2.content.h <= h, `④ ${w}×${h} ${st} 档 content 不越出屏幕底部`);
        ok(L2.content.y + L2.content.h <= L2.panel.y + L2.panel.h, `④ ${w}×${h} ${st} 档 content 不越出面板`);
        ok(L2.stage === st && L2.height === hh, `④ ${w}×${h} ${st} 档 stage/height 回显正确`);
      }
      // 动画中间值：高度用当前值，tab 行按当前高度走
      const mid = (peekH + drawerHeightFor('half', h)) / 2;
      const L3 = layoutDrawer({ screenW: w, screenH: h, stage: 'half', height: mid, tab: 'build', activeTab: 'build' });
      ok(near(L3.height, mid, 1e-9), `④ ${w}×${h} 动画中间值 height 原样回显`);
      ok(near(L3.panel.y, h - mid, 1e-9), `④ ${w}×${h} 动画中间值 panel.y = screenH − height`);
    }
  }
  // 安全区 / topLimit
  {
    const h = 844;
    const L = layoutDrawer({ screenW: 390, screenH: h, stage: 'half', height: drawerHeightFor('half', h), tab: 'build', activeTab: 'build', safeBottom: 34 });
    ok(L.content.y + L.content.h <= h - 34 + 1e-9, `④ safeBottom=34 时 content 底边 ${L.content.y + L.content.h} ≤ ${h - 34}`);
    const L2 = layoutDrawer({ screenW: 390, screenH: h, stage: 'half', height: drawerHeightFor('half', h), tab: 'build', activeTab: 'build', topLimit: 200 });
    ok(L2.content.y >= 200, `④ topLimit=200 时 content 顶边 ${L2.content.y} ≥ 200`);
  }
}

/* ================================================================ ⑥ 拖拽跟手 */
{
  const H = 844;
  let st = createDrawerState(H);
  st = drawerBeginDrag(st, H, st.height);
  ok(st.dragging === true, '⑥ beginDrag 后 dragging = true');
  ok(st.dragStartHeight === 60, '⑥ beginDrag 记录 dragStartHeight = 60');
  for (const h of [140, 260, 375, 500, 683, 743, 90]) {
    const moved = drawerDragTo(st, H, h);
    ok(moved.height === h, `⑥ 拖到 ${h}px ⇒ height 严格等于 ${h}（实得 ${moved.height}，不夹取到档位）`);
    ok(moved.dragging === true, '⑥ 拖动中 dragging 保持 true');
    ok(moved.dragMoved >= Math.abs(h - st.dragStartHeight), '⑥ dragMoved 累计离按下点的位移');
  }
  // 半像素也严格跟手
  const odd = drawerDragTo(st, H, 317.25);
  ok(odd.height === 317.25, `⑥ 拖到 317.25px ⇒ height 严格等于 317.25（实得 ${odd.height}）`);
  // 非法输入不产生 NaN
  const bad = drawerDragTo(st, H, Number.NaN);
  ok(Number.isFinite(bad.height), `⑥ 传入 NaN 时 height 仍为有限数（${bad.height}）`);
  // 位移小于 6px 判为点击（lead 侧判定用）
  const tiny = drawerDragTo(st, H, 64);
  ok(tiny.dragMoved === 4 && tiny.dragMoved < DRAWER_CLICK_SLOP, `⑥ 位移 4px < 6px 判为点击（dragMoved=${tiny.dragMoved}）`);
  const big = drawerDragTo(st, H, 300);
  ok(big.dragMoved >= DRAWER_CLICK_SLOP, `⑥ 位移 240px ≥ 6px 判为拖拽（dragMoved=${big.dragMoved}）`);
}

/* ================================================================ ⑦ 松手吸附 */
{
  const H = 844;
  const half = drawerHeightFor('half', H);
  const full = drawerHeightFor('full', H);
  const dragTo = (h: number): DrawerState => {
    let st = createDrawerState(H);
    st = drawerBeginDrag(st, H, st.height);
    st = drawerDragTo(st, H, h);
    return drawerEndDrag(st, H);
  };
  ok(dragTo(half - 5).stage === 'half', `⑦ half−5px 松手 → half（实得 ${dragTo(half - 5).stage}）`);
  ok(dragTo(half + 5).stage === 'half', `⑦ half+5px 松手 → half（实得 ${dragTo(half + 5).stage}）`);
  ok(dragTo(half).stage === 'half', '⑦ half 高度松手 → half');
  ok(dragTo(full - 5).stage === 'full', `⑦ full−5px 松手 → full（实得 ${dragTo(full - 5).stage}）`);
  ok(dragTo(full).stage === 'full', '⑦ full 高度松手 → full');
  ok(dragTo(full + 20).stage === 'full', `⑦ full+20px 松手 → full（实得 ${dragTo(full + 20).stage}）`);
  ok(dragTo(80).stage === 'peek', `⑦ full 拖到 80px 松手 → peek（实得 ${dragTo(80).stage}）`);
  ok(dragTo(80).height === 60, `⑦ full 拖到 80px 松手 ⇒ height = 60（实得 ${dragTo(80).height}）`);
  ok(dragTo(half + 5).height === half, `⑦ half 附近松手 ⇒ height = ${half}（实得 ${dragTo(half + 5).height}）`);
  const e = dragTo(300);
  ok(e.dragging === false, '⑦ 松手后 dragging = false');
  ok(e.animFrom === 300 && e.animTo === half, `⑦ 松手登记收敛动画 animFrom=300 → animTo=${half}（实得 ${e.animFrom}→${e.animTo}）`);
}

/* ================================================================ ⑧ 点把手 */
{
  const H = 844;
  const peek = createDrawerState(H);
  ok(peek.stage === 'peek' && peek.height === 60, '⑧ 初始态 = peek / 60px');
  const up = drawerTapHandle(peek, 1000, H);
  ok(up.stage === 'half', `⑧ peek 点把手 → half（实得 ${up.stage}）`);
  ok(up.animTo === drawerHeightFor('half', H), '⑧ peek 点把手登记 half 高度动画');
  ok(drawerIsAnimating(up, 1000) === true, '⑧ peek 点把手后处于动画中');
  const done = drawerTick(up, 1000 + DRAWER_ANIM_MS, H);
  ok(done.height === drawerHeightFor('half', H), `⑧ 动画结束后 height = half 高度（实得 ${done.height}）`);
  const down = drawerTapHandle(done, 2000, H);
  ok(down.stage === 'peek', `⑧ half 点把手 → peek（实得 ${down.stage}）`);
  const downDone = drawerTick(down, 2000 + DRAWER_ANIM_MS, H);
  ok(downDone.height === 60, `⑧ half 点把手落回 60px（实得 ${downDone.height}）`);
  // full 档点把手不动
  const full = drawerSetStage(done, 'full', 3000, H);
  const fullDone = drawerTick(full, 3000 + DRAWER_ANIM_MS, H);
  const tapFull = drawerTapHandle(fullDone, 4000, H);
  ok(tapFull.stage === 'full', `⑧ full 点把手 → full（实得 ${tapFull.stage}）`);
  ok(tapFull.height === fullDone.height, `⑧ full 点把手高度不变（${tapFull.height}）`);
}

/* ================================================================ ⑨ 380ms 动画 */
{
  const H = 844;
  const from = 60;
  const to = drawerHeightFor('half', H);
  const st = drawerSetStage(createDrawerState(H), 'half', 1000, H);
  ok(st.animMs === DRAWER_ANIM_MS, `⑨ 动画时长 = ${st.animMs}ms`);
  ok(st.animFrom === from && st.animTo === to, `⑨ animFrom/animTo = ${from}/${to}（实得 ${st.animFrom}/${st.animTo}）`);
  ok(st.animStartMs === 1000, '⑨ animStartMs = 起跑时刻');
  ok(drawerIsAnimating(st, 1000) === true, '⑨ 起跑瞬间算「动画中」');
  ok(drawerIsAnimating(st, 1379) === true, '⑨ 1379ms 仍在动画中');
  ok(drawerIsAnimating(st, 1380) === false, '⑨ 1380ms 动画结束');

  const t0 = drawerTick(st, 1000, H);
  ok(t0.height === from, `⑨ t=0 ⇒ height = from = ${from}（实得 ${t0.height}）`);
  const tm = drawerTick(st, 1190, H);
  ok(near(tm.height, from + (to - from) * 0.5, 1e-9), `⑨ t=190ms ⇒ height ≈ 中点 ${from + (to - from) * 0.5}（实得 ${tm.height}）`);
  const t1 = drawerTick(st, 1380, H);
  ok(t1.height === to, `⑨ t=380ms ⇒ height = to = ${to}（实得 ${t1.height}）`);
  const t2 = drawerTick(st, 5000, H);
  ok(t2.height === to, `⑨ t≫380ms ⇒ height 仍是 to（实得 ${t2.height}）`);
  ok(drawerIsAnimating(t2, 5000) === false, '⑨ 动画结束后不再是「动画中」');
  // 逐帧单调、不越界
  let prev = -Infinity, mono = true, bounded = true;
  for (let ms = 1000; ms <= 1400; ms += 10) {
    const h = drawerTick(st, ms, H).height;
    if (h < prev - 1e-9) { mono = false; }
    if (h < from - 1e-9 || h > to + 1e-9) { bounded = false; }
    prev = h;
  }
  ok(mono, '⑨ 逐帧单调不减（不抖）');
  ok(bounded, '⑨ 插值全程在 [from, to] 内（不过冲）');

  // drawerEasing：两端 0/1、中点 0.5、单调不减
  ok(drawerEasing(0) === 0, '⑨ easing(0) = 0');
  ok(drawerEasing(1) === 1, '⑨ easing(1) = 1');
  ok(near(drawerEasing(0.5), 0.5, 1e-12), `⑨ easing(0.5) = 0.5（实得 ${drawerEasing(0.5)}）`);
  ok(drawerEasing(-5) === 0 && drawerEasing(5) === 1, '⑨ easing 越界被夹取到 [0,1]');
  let ePrev = -1, eMono = true;
  for (let i = 0; i <= 1000; i++) {
    const v = drawerEasing(i / 1000);
    if (v < ePrev - 1e-12) { eMono = false; }
    if (!(v >= 0 && v <= 1)) { eMono = false; }
    ePrev = v;
  }
  ok(eMono, '⑨ easing 在 [0,1] 上单调不减且恒在 [0,1] 内');
}

/* ================================================================ ⑩ framing */
{
  const p = drawerFraming('peek');
  ok(p.zoom === 1.0 && p.dyFrac === 0 && p.scale === 1.0, `⑩ peek framing = 1.0 / 0 / 1.0（实得 ${p.zoom}/${p.dyFrac}/${p.scale}）`);
  const h = drawerFraming('half');
  ok(h.zoom === 1.39 && h.dyFrac === -0.06 && h.scale === 0.72, `⑩ half framing = 1.39 / −0.06 / 0.72（实得 ${h.zoom}/${h.dyFrac}/${h.scale}）`);
  const f = drawerFraming('full');
  ok(f.zoom === 1.82 && f.dyFrac === -0.385 && f.scale === 0.55, `⑩ full framing = 1.82 / −0.385 / 0.55（实得 ${f.zoom}/${f.dyFrac}/${f.scale}）`);
  ok(DRAWER_CAM_ZOOM.peek === 1.0 && DRAWER_CAM_ZOOM.half === 1.39 && DRAWER_CAM_ZOOM.full === 1.82, '⑩ DRAWER_CAM_ZOOM = 1.0/1.39/1.82');
  ok(DRAWER_ISLAND_DY.peek === 0 && DRAWER_ISLAND_DY.half === -0.06 && DRAWER_ISLAND_DY.full === -0.385, '⑩ DRAWER_ISLAND_DY = 0/−0.06/−0.385');
  ok(DRAWER_ISLAND_SCALE.peek === 1.0 && DRAWER_ISLAND_SCALE.half === 0.72 && DRAWER_ISLAND_SCALE.full === 0.55, '⑩ DRAWER_ISLAND_SCALE = 1.0/0.72/0.55');
  // 390×844 实测上移像素：half −50.6px / full −325px
  ok(near(drawerFraming('half').dyFrac * 844, -50.64, 1e-9), `⑩ 390×844 half 上移 ${(drawerFraming('half').dyFrac * 844).toFixed(2)}px（说明.md 实测 −50.6px）`);
  ok(near(drawerFraming('full').dyFrac * 844, -324.94, 1e-9), `⑩ 390×844 full 上移 ${(drawerFraming('full').dyFrac * 844).toFixed(2)}px（说明.md 实测 −325px）`);
  // framing 返回新对象（不改入参）
  const a = drawerFraming('half');
  const b = drawerFraming('half');
  ok(a !== b && near(a.zoom, b.zoom, 0), '⑩ drawerFraming 每次返回新对象');
}

/* ================================================================ ⑪ 纯函数 / 有限数 */
{
  const H = 844;
  const base = createDrawerState(H);
  const snapshot = JSON.stringify(base);
  const frozen = Object.freeze({ ...base });
  const n1 = drawerBeginDrag(frozen, H, frozen.height);
  const n2 = drawerDragTo(n1, H, 333);
  const n3 = drawerEndDrag(n2, H);
  const n4 = drawerSetStage(n3, 'full', 100, H);
  const n5 = drawerTapHandle(n4, 200, H);
  const n6 = drawerTick(n5, 300, H);
  ok(JSON.stringify(base) === snapshot, '⑪ 状态机不改入参（原状态逐字不变）');
  ok(n1 !== frozen && n2 !== n1 && n3 !== n2 && n4 !== n3 && n6 !== n5, '⑪ 状态机每一步都返回新对象');
  for (const s of [n1, n2, n3, n4, n5, n6]) {
    const nums = [s.stage.length, s.height, s.animFrom, s.animTo, s.animStartMs, s.animMs, s.dragStartHeight, s.dragMoved];
    ok(nums.every((v) => Number.isFinite(v)), `⑪ 状态数值全有限（${JSON.stringify(nums)}）`);
  }
  // layoutDrawer 不改入参
  const inp = Object.freeze({ screenW: 390, screenH: 844, stage: 'half' as DrawerStage, height: 380, tab: 'build' as DrawerTabId, activeTab: 'build' as DrawerTabId });
  const inpSnapshot = JSON.stringify(inp);
  const lay = layoutDrawer(inp);
  ok(JSON.stringify(inp) === inpSnapshot, '⑪ layoutDrawer 不改入参');
  const layNums = [lay.height, lay.panel.x, lay.panel.y, lay.panel.w, lay.panel.h, lay.handle.y, lay.handle.h, lay.tabRow.y, lay.tabRow.h, lay.content.y, lay.content.h, lay.tabFont];
  ok(layNums.every((v) => Number.isFinite(v)), `⑪ 排版数值全有限（${JSON.stringify(layNums)}）`);
  // 非法输入不产生 NaN
  const bad = layoutDrawer({ screenW: Number.NaN, screenH: Number.NaN, stage: 'peek', height: Number.NaN, tab: 'build', activeTab: 'build' });
  const badNums = [bad.height, bad.panel.y, bad.panel.h, bad.tabRow.y, bad.content.y, bad.content.h, bad.tabFont];
  ok(badNums.every((v) => Number.isFinite(v)), `⑪ 非法输入不产生 NaN（${JSON.stringify(badNums)}）`);
  ok(drawerHeightFor('half', Number.NaN) === 0, '⑪ 非法屏高 ⇒ half 高度 0（有限）');
  ok(drawerStageForHeight(Number.NaN, H) === 'peek', '⑪ 非法高度 ⇒ 吸附 peek');
  ok(drawerTabFontSize(Number.NaN) === 13, '⑪ 非法屏宽 ⇒ 字号 13');
}

/* ================================================================ ⑫ 端到端：三档往返 */
{
  const H = 844;
  const peek = createDrawerState(H);
  ok(peek.stage === 'peek' && peek.height === 60, '⑫ 初始 peek / 60px');
  // peek → 拖到 full → 松手 → full
  let s = drawerBeginDrag(peek, H, peek.height);
  s = drawerDragTo(s, H, drawerHeightFor('full', H));
  s = drawerEndDrag(s, H);
  ok(s.stage === 'full', '⑫ 拖到 full 高度松手 → full');
  // full 一路下拉到 peek
  s = drawerBeginDrag(s, H, s.height);
  s = drawerDragTo(s, H, 120);
  s = drawerEndDrag(s, H);
  ok(s.stage === 'peek', '⑫ full 下拉到 120px 松手 → peek');
  // 切 tab 不改高度/档位（本模块只提供几何，stage/height 由调用方保持）
  const layout = layoutDrawer({ screenW: 390, screenH: H, stage: 'peek', height: 60, tab: 'land', activeTab: 'land' });
  ok(layout.stage === 'peek' && layout.height === 60, '⑫ 切 tab 后 stage/height 不变');
}

/* ================================================================ 输出 */
const out = { checks, fails: fails.length, list: fails.slice(0, 30) };
const outFile = process.argv[2] ?? '/tmp/s24-drawer-state.json';
writeFileSync(outFile, JSON.stringify(out, null, 1));
if (fails.length > 0) {
  console.error(`S-24 抽屉状态机测试：${checks} 断言，失败 ${fails.length} 条`);
  for (const f of fails.slice(0, 20)) { console.error(' - ' + f); }
  process.exit(1);
}
console.log(`S-24 抽屉状态机测试：${checks} 断言全部通过（结果：${outFile}）`);
console.log(`  关键数字：390×844 half = ${drawerHeightFor('half', 844)}px（契约未取整 379.8）｜ full = ${drawerHeightFor('full', 844)}px`);
console.log(`  关键数字：320 宽每格 tab = ${drawerTabCells(320)[0].w}px（契约值 52.8）｜ 390 宽每格 tab = ${drawerTabCells(390)[0].w}px`);
