/**
 * S-24 · 底部下栏抽屉 HUD · 状态机与几何纯函数（S1 实现）。
 * -----------------------------------------------------------------------------
 * 规格来源：`docs/S-24-抽屉契约.md` §1/§3（定稿参数，数值不可改）
 *           + `tasks-out/S-23-UI-DEMO/demo/v2-ui-demo.html`（原型实测）。
 *
 * 本文件只做**纯计算**：不 import three / DOM / canvas / session，可在 Node 里直接单测。
 * 绘制（画圆角、画字、画金币胶囊）由 lead 在 `src/ui/hud.ts` 里按本文件的结果完成。
 *
 * 三档（定稿）：
 *   peek  = 露把手 60px（tab 行**完全移出屏幕**，视口内可见高度 = 0）
 *   half  = 屏高 45%    full = 屏高 88%
 *   岛景缩放 1.0 / 0.72 / 0.55；岛景上移 ty = 0 / −6% / −38.5% 屏高
 *   相机 framing（相机距离倍数 = 1 ÷ 岛景缩放）1.0 / 1.39 / 1.82
 *   抽屉动画 380ms；金币胶囊位移淡入 220ms（本模块只暴露常量，不画金币）
 *
 * 约定（与契约 §3「语义约定」一致）：
 *   · `height` = 抽屉面板高度（px），自屏幕底边往上量；`panel.y = screenH - height`。
 *   · `handle` = 面板顶部一条（高 60px；peek 时整条 60px 都是把手）。
 *   · `tabRow` 贴在 handle 下方；peek 时 `tabRow.y ≥ screenH` ⇒ 视口内不可见（tabVisible = false）。
 *   · `content` = tab 行下方 → 面板底部（上下各留 12px 内边距；底部另让开安全区）。
 *
 * 状态机用法（lead 接线）：
 *   初始      `st = createDrawerState(screenH)`                 （peek）
 *   按下      `st = drawerBeginDrag(st, screenH, st.height)`
 *   拖动      `st = drawerDragTo(st, screenH, 手指推出的高度)`      （跟手：height 严格等于传入值）
 *   松手      `st = drawerEndDrag(st, screenH)`                   （吸附最近档）
 *   每帧      `st = drawerTick(st, nowMs, screenH)`                （380ms 插值）
 *   点把手    `st = drawerTapHandle(st, nowMs, screenH)`          （peek ⇄ half；full 不动）
 *   切档      `st = drawerSetStage(st, 'half', nowMs, screenH)`
 *
 * 时间基准：`nowMs` 由调用方给（`Date.now()` 或 `performance.now()` 均可，只要单调）。
 * `drawerEndDrag` 按契约**没有时间入参**，因此它把动画登记为「待启动」：
 *   `animStartMs = -1`（哨兵）表示还没起跑；首个 `drawerTick(nowMs)` 会用该 nowMs 作为动画起点。
 *   `drawerEndDrag` 本身**立即**把 `height` 置为吸附后的目标高度（便于断言「松手即吸附」），
 *   同时保留 `animFrom = 松手时的高度`、`animTo = 目标高度`，随后的 drawerTick 会从手指位置收敛到目标。
 */

/* ============================================================ 常量（契约 §3） */

export const DRAWER_PEEK_PX = 60;         // px
export const DRAWER_HALF_FRAC = 0.45;     // 屏高比例
export const DRAWER_FULL_FRAC = 0.88;     // 屏高比例
export const DRAWER_ANIM_MS = 380;
export const DRAWER_COIN_MOVE_MS = 220;
export const DRAWER_TAB_COUNT = 5;
export const DRAWER_TAB_PAD = 12;
export const DRAWER_TAB_GAP = 8;
export const DRAWER_TAB_RADIUS = 9;
export const DRAWER_TAB_BORDER = 1;
export const DRAWER_TAB_BORDER_COLOR = '#D8C7A4';
export const DRAWER_TAB_SELECT_BG = 'rgba(247,197,92,0.18)';
export const DRAWER_TAB_SELECT_BORDER = '#C99A3F';
export const DRAWER_TAB_ROW_H = 34;
export const DRAWER_CLICK_SLOP = 6;       // 位移 < 6px 判为点击

/* ============================================================ 类型 */

export type DrawerStage = 'peek' | 'half' | 'full';
export type DrawerTabId = 'build' | 'land' | 'resident' | 'block' | 'more';

export interface DrawerTabSpec { readonly id: DrawerTabId; readonly label: string }
/** 五个分类 tab（顺序 = build,land,resident,block,more；文案同 demo）。 */
export const DRAWER_TABS: ReadonlyArray<DrawerTabSpec> = [
  { id: 'build', label: '建筑' },
  { id: 'land', label: '土地' },
  { id: 'resident', label: '居民' },
  { id: 'block', label: '街区' },
  { id: 'more', label: '其他' }
];

export interface DrawerRect { readonly x: number; readonly y: number; readonly w: number; readonly h: number }

export interface DrawerFraming {
  readonly zoom: number;      // 相机 zoom 目标（相机距离倍数 = 1 ÷ 岛景缩放）
  readonly dyFrac: number;    // 岛景上移比例（屏高，负 = 上）
  readonly scale: number;     // 岛景缩放
}

/** 岛景上移比例（屏高，负 = 上）：peek 0 / half −6% / full −38.5%（390×844 实测 0 / −50.6px / −325px）。 */
export const DRAWER_ISLAND_DY: Readonly<Record<DrawerStage, number>> = { peek: 0, half: -0.06, full: -0.385 };
/** 相机 framing（相机距离倍数 = 1 ÷ 岛景缩放）。 */
export const DRAWER_CAM_ZOOM: Readonly<Record<DrawerStage, number>> = { peek: 1.0, half: 1.39, full: 1.82 };
/** 岛景缩放。 */
export const DRAWER_ISLAND_SCALE: Readonly<Record<DrawerStage, number>> = { peek: 1.0, half: 0.72, full: 0.55 };

/* ============================================================ 内部工具 */

/** 有限数兜底（非有限 → 兜底值，保证任何输出都是有限数、不出现 NaN）。 */
const fin = (v: unknown, fallback = 0): number => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
/** 夹取到 [lo, hi]。 */
const clamp = (v: number, lo: number, hi: number): number => (hi < lo ? lo : Math.min(hi, Math.max(lo, v)));
/** 屏幕高（非法值按 0 处理）。 */
const screenHOf = (screenH: unknown): number => Math.max(0, fin(screenH));

/* ============================================================ 几何纯函数 */

/** 三档的相机 / 岛景 framing（纯函数，返回新对象）。 */
export function drawerFraming(stage: DrawerStage): DrawerFraming {
  const s: DrawerStage = stage === 'half' || stage === 'full' ? stage : 'peek';
  return { zoom: DRAWER_CAM_ZOOM[s], dyFrac: DRAWER_ISLAND_DY[s], scale: DRAWER_ISLAND_SCALE[s] };
}

/**
 * 某档的抽屉高度（px）：
 *   peek = 60；half = round(屏高 × 0.45)；full = round(屏高 × 0.88)。
 * （390×844 ⇒ peek 60 / half 380 / full 743；原型未取整值 379.8 / 742.72。）
 */
export function drawerHeightFor(stage: DrawerStage, screenH: number): number {
  const h = screenHOf(screenH);
  if (stage === 'half') { return Math.round(h * DRAWER_HALF_FRAC); }
  if (stage === 'full') { return Math.round(h * DRAWER_FULL_FRAC); }
  return DRAWER_PEEK_PX;
}

/** 把任意高度吸附到**最近**的一档（等距时取更小的那一档）。 */
export function drawerStageForHeight(height: number, screenH: number): DrawerStage {
  const h = fin(height);
  const peek = drawerHeightFor('peek', screenH);
  const half = drawerHeightFor('half', screenH);
  const full = drawerHeightFor('full', screenH);
  let best: DrawerStage = 'peek';
  let bestD = Math.abs(h - peek);
  const halfD = Math.abs(h - half);
  if (halfD < bestD) { best = 'half'; bestD = halfD; }
  const fullD = Math.abs(h - full);
  if (fullD < bestD) { best = 'full'; bestD = fullD; }
  return best;
}

/** tab 字号：屏宽 ≤ 330 一律 12px，否则 13px（390 / 414 / 430 ⇒ 13px）。 */
export function drawerTabFontSize(screenW: number): number {
  const w = fin(screenW);
  return w > 0 && w <= 330 ? 12 : 13;
}

/**
 * tab 行五等分：每格宽 = (屏宽 − 12×2 − 8×4) / 5，整排左右各留 12px、格间 gap 8px。
 * 返回的矩形 `y = 0`、`h = DRAWER_TAB_ROW_H`（行位置由 layoutDrawer 填）。
 * 390 ⇒ 每格 66.8px（末格右缘 378 = 390 − 12）；320 ⇒ 每格 52.8px（末格右缘 308 = 320 − 12）。
 */
export function drawerTabCells(screenW: number): DrawerRect[] {
  const w = Math.max(0, fin(screenW));
  const cellW = (w - DRAWER_TAB_PAD * 2 - DRAWER_TAB_GAP * (DRAWER_TAB_COUNT - 1)) / DRAWER_TAB_COUNT;
  const cells: DrawerRect[] = [];
  for (let i = 0; i < DRAWER_TAB_COUNT; i++) {
    cells.push({ x: DRAWER_TAB_PAD + i * (cellW + DRAWER_TAB_GAP), y: 0, w: cellW, h: DRAWER_TAB_ROW_H });
  }
  return cells;
}

/* ============================================================ 排版 */

export interface DrawerLayoutInput {
  readonly screenW: number; readonly screenH: number;
  readonly stage: DrawerStage;   // 当前目标档
  readonly height: number;       // 当前高度 px（动画中间值也用它）
  readonly tab: DrawerTabId;
  readonly activeTab: DrawerTabId;
  readonly safeBottom?: number;
  readonly topLimit?: number;    // 内容区上边界（默认 = 顶栏下沿）
}

export interface DrawerLayout {
  readonly stage: DrawerStage;
  readonly height: number;
  readonly panel: DrawerRect;    // 抽屉面板（贴底，x=0, w=屏宽）
  readonly handle: DrawerRect;   // 把手（面板顶部 60px 内的一条）
  readonly tabRow: DrawerRect;   // tab 行（peek 时 y 超出屏幕 = 移出屏幕）
  readonly tabCells: ReadonlyArray<DrawerRect>;
  readonly content: DrawerRect;  // 列表内容区（tab 行之下、面板底部之上）
  readonly tabFont: number;
  readonly tabVisible: boolean;  // peek ⇒ false（视口内可见高度 = 0）
}

/**
 * 抽屉排版（纯函数）。
 *   panel   贴底：{ x:0, y: screenH - height, w: screenW, h: height }
 *   handle  面板顶部一条：{ x:0, y: panel.y, w: screenW, h: min(60, height) }
 *   tabRow  贴在 handle 下方：{ x:0, y: panel.y + handle.h, w: screenW, h: 34 }
 *   content tab 行下方 12px → 面板底部上方 12px（底部另让开 safeBottom）
 *   peek 时 tabRow.y = screenH（完全移出屏幕）、tabVisible = false、content.h ≤ 0（内容区为空）。
 */
export function layoutDrawer(inp: DrawerLayoutInput): DrawerLayout {
  const screenW = Math.max(0, fin(inp.screenW));
  const screenH = screenHOf(inp.screenH);
  const height = Math.max(0, fin(inp.height));

  const panel: DrawerRect = { x: 0, y: screenH - height, w: screenW, h: height };
  const handleH = Math.min(DRAWER_PEEK_PX, height);
  const handle: DrawerRect = { x: 0, y: panel.y, w: screenW, h: handleH };
  const tabRow: DrawerRect = { x: 0, y: panel.y + handleH, w: screenW, h: DRAWER_TAB_ROW_H };

  const tabCells: DrawerRect[] = drawerTabCells(screenW).map((c) => ({ x: c.x, y: tabRow.y, w: c.w, h: DRAWER_TAB_ROW_H }));

  const bottomInset = Math.max(DRAWER_TAB_PAD, fin(inp.safeBottom));
  const panelBottom = screenH;
  const bandTop = tabRow.y + tabRow.h;                                  // tab 行下沿
  // 内容区 = tab 行下沿（+12 内边距，且让开 topLimit）→ 面板底边（−12 / −安全区）。
  // peek 时 tab 行已在屏外 ⇒ 上沿 > 下沿 ⇒ h 为**负数**（内容区为空）；绘制前请先判 h > 0。
  const contentTop = Math.max(bandTop + DRAWER_TAB_PAD, fin(inp.topLimit));
  const contentBottom = Math.min(panelBottom - bottomInset, panelBottom);
  const content: DrawerRect = { x: 0, y: contentTop, w: screenW, h: contentBottom - contentTop };

  const tabFont = drawerTabFontSize(screenW);
  // tab 行与视口有交集才算可见（peek 时 tabRow.y = screenH ⇒ 不可见）。
  const tabVisible = tabRow.y < screenH && tabRow.y + tabRow.h > 0;

  return { stage: inp.stage, height, panel, handle, tabRow, tabCells, content, tabFont, tabVisible };
}

/* ============================================================ 状态机 */

export interface DrawerState {
  readonly stage: DrawerStage;
  readonly height: number;
  readonly dragging: boolean;
  readonly animFrom: number; readonly animTo: number; readonly animStartMs: number; readonly animMs: number;
  readonly dragStartHeight: number; readonly dragMoved: number;
}

/** `animStartMs = -1` = 动画「已登记但还没起跑」（首个 drawerTick 用它的 nowMs 当起点）。 */
const ANIM_PENDING = -1;

/**
 * 初始状态：peek（露把手 60px）。
 * `animMs` 恒为 DRAWER_ANIM_MS（抽屉动画时长）；「当前没有动画在跑」由 `animFrom === animTo` 表达。
 */
export function createDrawerState(screenH: number): DrawerState {
  const h = drawerHeightFor('peek', screenH);
  return {
    stage: 'peek', height: h, dragging: false,
    animFrom: h, animTo: h, animStartMs: 0, animMs: DRAWER_ANIM_MS,
    dragStartHeight: h, dragMoved: 0
  };
}

/**
 * 按下把手：进入拖拽态。
 * `startHeight` = 按下瞬间的抽屉高度（一般是 st.height）。
 */
export function drawerBeginDrag(s: DrawerState, screenH: number, startHeight: number): DrawerState {
  const h = Math.max(0, fin(startHeight, s.height));
  return {
    ...s,
    dragging: true,
    height: h,
    stage: drawerStageForHeight(h, screenH),
    dragStartHeight: h,
    dragMoved: 0,
    animFrom: h, animTo: h, animStartMs: s.animStartMs, animMs: DRAWER_ANIM_MS
  };
}

/**
 * 拖到某个高度：**跟手**——height 严格等于传入值（不做任何夹取、不吸附到档位）。
 * 同时累计 `dragMoved`（离按下点的最大位移，px）供 lead 判定「点击 vs 拖拽」（阈值 DRAWER_CLICK_SLOP = 6）。
 */
export function drawerDragTo(s: DrawerState, screenH: number, height: number): DrawerState {
  const h = fin(height, s.height);           // 非有限输入 ⇒ 保持原高度
  const moved = Math.max(s.dragMoved, Math.abs(h - s.dragStartHeight));
  return {
    ...s,
    dragging: true,
    height: h,
    stage: drawerStageForHeight(h, screenH),
    dragMoved: moved,
    animFrom: h, animTo: h, animStartMs: s.animStartMs, animMs: DRAWER_ANIM_MS
  };
}

/**
 * 松手：吸附到**最近**的一档。
 * · `stage` 立即变成吸附后的档；
 * · `height` 立即置为该档高度（松手即吸附）；
 * · 同时登记一次 380ms 收敛动画：`animFrom` = 松手时的高度（手指位置）、`animTo` = 目标高度、
 *   `animStartMs = -1`（待启动）——首个 `drawerTick(nowMs)` 会从手指位置开始插值到目标。
 */
export function drawerEndDrag(s: DrawerState, screenH: number): DrawerState {
  const stage = drawerStageForHeight(s.height, screenH);
  const target = drawerHeightFor(stage, screenH);
  return {
    ...s,
    stage,
    height: target,
    dragging: false,
    animFrom: s.height, animTo: target, animStartMs: ANIM_PENDING, animMs: DRAWER_ANIM_MS,
    dragMoved: s.dragMoved
  };
}

/**
 * 切档（带 380ms 动画）：`animFrom` = 当前高度，`animTo` = 目标档高度，动画从 nowMs 起跑。
 * 目标高度 = 当前高度时不动（animFrom === animTo ⇒ 不算动画中）。
 */
export function drawerSetStage(s: DrawerState, stage: DrawerStage, nowMs: number, screenH: number): DrawerState {
  const target = drawerHeightFor(stage, screenH);
  return {
    ...s,
    stage,
    height: s.height,
    dragging: false,
    animFrom: s.height, animTo: target, animStartMs: fin(nowMs), animMs: DRAWER_ANIM_MS,
    dragMoved: 0
  };
}

/** 点把手：peek ⇄ half；full 档点把手不动。 */
export function drawerTapHandle(s: DrawerState, nowMs: number, screenH: number): DrawerState {
  const next: DrawerStage = s.stage === 'peek' ? 'half' : s.stage === 'half' ? 'peek' : 'full';
  if (next === s.stage) { return s; }
  return drawerSetStage(s, next, nowMs, screenH);
}

/** 是否正在做 380ms 动画（animMs = 0 或起终点相同 ⇒ 不算）。 */
export function drawerIsAnimating(s: DrawerState, nowMs: number): boolean {
  if (!(s.animMs > 0) || s.animTo === s.animFrom) { return false; }
  if (s.animStartMs < 0) { return true; }               // 待启动
  return fin(nowMs) < s.animStartMs + s.animMs;
}

/**
 * 动画插值：t = (nowMs − animStartMs) / animMs，e = drawerEasing(t)，height = from + (to − from) × e。
 *   t = 0   ⇒ height = animFrom
 *   t ≥ 1   ⇒ height = animTo（动画结束，animMs 归 0）
 * 非动画态原样返回（不改入参）。
 */
export function drawerTick(s: DrawerState, nowMs: number, screenH: number): DrawerState {
  void screenH;
  if (!(s.animMs > 0) || s.animTo === s.animFrom) { return s; }
  const now = fin(nowMs);
  const start = s.animStartMs < 0 ? now : s.animStartMs;
  const t = clamp((now - start) / s.animMs, 0, 1);
  if (t >= 1) {
    // 动画结束：高度 = animTo，animFrom === animTo ⇒ 之后不再是「动画中」。
    return { ...s, height: s.animTo, animFrom: s.animTo, animTo: s.animTo, animStartMs: start };
  }
  const e = drawerEasing(t);
  return { ...s, height: s.animFrom + (s.animTo - s.animFrom) * e, animStartMs: start };
}

/**
 * 缓动：0..1 → 0..1（两端 0 / 1，中点恰好 0.5，单调不减）。
 * smoothstep（3t² − 2t³）：契约 §3 要求「两端 0/1，中点 0.5」——原型的 cubic-bezier(.22,.61,.36,1)
 * 中点约 0.87（前端加载），与契约的 0.5 不符，故本实现用 smoothstep。
 */
export function drawerEasing(t: number): number {
  const x = clamp(fin(t), 0, 1);
  return x * x * (3 - 2 * x);
}
