/**
 * S-24 · 街区 tab（block）· 视图模型 + 纯布局函数。
 * -----------------------------------------------------------------------------
 * 契约：`docs/S-24-抽屉契约.md` §4 —— `blockTabRows(input)` → **目标提示**（当前该升什么、还差多少金币）
 * + **区 / 市政厅升级行**；升级行 kind 与 `src/ui/hud-layout.ts` 的 `BlockRowKind` **完全一致**：
 * `'ok' | 'poor' | 'max' | 'none' | 'pending'`（本文件用 `import type` 直接引该类型，编译期保证同一份定义）。
 *
 * 硬边界（勿越界）：
 *  · 不画 canvas、不碰 DOM、不 import three；
 *  · 不 import `src/ui/hud.ts`、不 import `src/game/session.ts`（数据一律以**纯数据入参**传入）；
 *  · 只做「行数据 / 排序 / 价格文案 / 命中矩形」四件事，不做任何经济计算。
 *
 * 数字格式化一律走 `src/game/format.ts` 的既有纯函数（只读、未改动）。
 *
 * 排序（**固定且稳定**，回归断言可直接依赖）：
 *   1) 目标提示行（id = 'goal'，纯展示，**不参与点击**）
 *   2) 市政厅升级行（id = 'hall'）
 *   3) 区（城区）升级行（id = 'district'）
 * 任一入参为 null / 缺省时该行不出现，其余行**不重排、不合并**。
 */

// @ts-expect-error TS5097：仓库 tsconfig 未开 `allowImportingTsExtensions`；此处显式写 `.ts` 扩展名，
// 使本模块能被 Node 24 直接 import（类型剥离），esbuild 打包同样可解析（已实测）。
import { fmtInt, fmtRateMilli2 } from '../../game/format.ts';
// 类型引用用 `import type`（编译期整条擦除，运行期不产生任何模块依赖）。
import type { BlockRowKind } from '../hud-layout';
// 通用行模型 / 矩形统一来自 `src/ui/tabs/tabs-common.ts`（S2 维护的唯一权威来源），这里只再导出、不重复定义。
import type { TabRect, TabRowModel, TabListModel, TabHitRect } from './tabs-common';

export type { BlockRowKind };
// 单一权威来源：共享模型类型只在 tabs-common.ts 定义，这里再导出一次便于接线方按 tab 取用。
export type { TabRowModel, TabListModel, TabRect, TabHitRect } from './tabs-common';

/* ============================== 契约 §4 通用行模型 ============================== */

/** 内容区矩形（抽屉列表内容区）。 */
export type TabContentRect = TabRect;

/** 一行的命中信息（在通用命中矩形上加「是否可点」）。 */
export interface TabRowHit extends TabHitRect {
  /** false = 纯展示行（如目标提示），调用方不应把它当可点项。 */
  readonly interactive: boolean;
}

/* ================================= 街区 tab 模型 ================================= */

/** 目标提示的纯数据入参：当前该升什么、还差多少金币。 */
export interface BlockGoalInput {
  /** 目标名，如 "区 Lv2" / "居民楼开业"。 */
  readonly target: string;
  /** 目标花费（金币，整数）。 */
  readonly priceCoins: number;
  /** 还差多少金币（>0 = 金币不足；0 = 已够）。 */
  readonly shortfallCoins?: number;
  /** 目标之后的下一步（可选），如 "→ 居民楼开业 80"。 */
  readonly nextText?: string;
}

/** 升级行的纯数据入参（价格 / 缺口 / 产速全部由调用方给，本文件只做文案）。 */
export interface BlockUpgradeInput {
  /** 行 id（默认 'hall' / 'district'，由调用方显式给，保证命中断言稳定）。 */
  readonly id: string;
  /** 行标题，如 "市政厅" / "城区"。 */
  readonly title: string;
  /** 等级文案，如 "Lv 3/20"。 */
  readonly levelText?: string;
  /** 升级态（与 hud-layout 的 BlockRowKind 完全一致）。 */
  readonly kind: BlockRowKind;
  /** 升级价（金币，整数）；kind = 'max' / 'none' 时忽略。 */
  readonly priceCoins?: number;
  /** 还差多少金币（仅 kind = 'poor' 有意义）。 */
  readonly shortfallCoins?: number;
  /** 每级增益百分数（纯文案，如 "4" / "6"）。 */
  readonly gainPct?: string;
  /** 升级后每分钟增加（毫币/分，用 `fmtRateMilli2` 格式化）。 */
  readonly deltaMilliPerMin?: number;
  /** 已格式化好的产速文案（给了就优先用它）。 */
  readonly deltaText?: string;
  /** 徽标短文案（不给则由 gainPct 推导 " +6%"）。 */
  readonly badge?: string;
  /** 强制禁用（缺省按 kind 推导）。 */
  readonly disabled?: boolean;
}

/** 目标提示行（纯展示，不参与点击）。 */
export interface BlockGoalRow extends TabRowModel {
  readonly type: 'goal';
  readonly actionable: false;
  /** 窄屏紧凑同义文案（数字同源，语义相同）。 */
  readonly compactText: string;
}

/** 升级行（区 / 市政厅）。 */
export interface BlockUpgradeRow extends TabRowModel {
  readonly type: 'upgrade';
  readonly kind: BlockRowKind;
  /** 价格文案（"1,200 金币" / "1,200 金币 · 还差 300 金币" / "已满级" …）。 */
  readonly priceText: string;
  /** 是否可点（kind = 'ok' / 'poor' 为 true）。 */
  readonly actionable: boolean;
}

/** 街区 tab 的行（目标提示行 + 升级行）。 */
export type BlockTabRow = BlockGoalRow | BlockUpgradeRow;

/** `blockTabRows` 的入参（全部纯数据）。 */
export interface BlockTabInput {
  /** 目标提示（null = 本轮没有目标提示行）。 */
  readonly goal?: BlockGoalInput | null;
  /** 市政厅升级行（null = 不显示）。 */
  readonly hall?: BlockUpgradeInput | null;
  /** 区（城区）升级行（null = 不显示）。 */
  readonly district?: BlockUpgradeInput | null;
}

/** 街区 tab 的视图模型。 */
export interface BlockTabModel extends TabListModel {
  readonly rows: ReadonlyArray<BlockTabRow>;
  /** 目标提示行（= rows 里那条 type='goal' 的行；没有则为 null）。 */
  readonly goal: BlockGoalRow | null;
}

/* ================================== 常量 ================================== */

/** 目标提示行 id。 */
export const BLOCK_GOAL_ROW_ID = 'goal';
/** 市政厅行 id（默认值，调用方也可自定义）。 */
export const BLOCK_HALL_ROW_ID = 'hall';
/** 区（城区）行 id（默认值）。 */
export const BLOCK_DISTRICT_ROW_ID = 'district';

/** 目标提示行高（与 hud-layout 的 goalHintRect 行高一致：22）。 */
export const BLOCK_GOAL_H = 22;
/** 升级行高。 */
export const BLOCK_ROW_H = 56;
/** 行间距。 */
export const BLOCK_ROW_GAP = 8;
/** 内容区左右内边距。 */
export const BLOCK_ROW_PAD_X = 12;
/** 空列表文案。 */
export const BLOCK_TAB_EMPTY_TEXT = '暂无可升级项';

/* ================================== 文案生成 ================================== */

/**
 * 目标提示完整文案（语义与 S-21 的 `goalHintText` 一致）：
 * 有缺口 → `下个目标：区 Lv2（还差 2,040 金币）`；不缺 → `下个目标：区 Lv2（2,100 金币）`。
 */
export function blockGoalText(g: BlockGoalInput): string {
  const price = nonNegInt(g.priceCoins);
  const short = nonNegInt(g.shortfallCoins);
  const cost = short > 0 ? `还差 ${fmtInt(short)} 金币` : `${fmtInt(price)} 金币`;
  const head = `下个目标：${g.target}（${cost}）`;
  if (!g.nextText) { return head; }
  return g.nextText.startsWith('→') ? `${head}${g.nextText}` : `${head} ${g.nextText}`;
}

/** 目标提示紧凑文案（窄屏用；数字同源、语义相同）。 */
export function blockGoalCompactText(g: BlockGoalInput): string {
  const price = nonNegInt(g.priceCoins);
  const short = nonNegInt(g.shortfallCoins);
  const n = short > 0 ? short : price;
  return `下个目标：${g.target} ${fmtInt(n)} 金币`;
}

/** 目标提示行模型。 */
export function blockGoalRow(g: BlockGoalInput): BlockGoalRow {
  return {
    id: BLOCK_GOAL_ROW_ID,
    type: 'goal',
    title: blockGoalText(g),
    disabled: true,
    actionable: false,
    compactText: blockGoalCompactText(g),
  };
}

/** 价格文案（按 kind 固定规则，回归可断言）。 */
function upgradePriceText(kind: BlockRowKind, price: number, short: number): string {
  if (kind === 'max') { return '已满级'; }
  if (kind === 'none') { return '暂无可升级'; }
  if (kind === 'pending') { return '离线结算中'; }
  if (kind === 'poor') {
    if (short <= 0) { return `${fmtInt(price)} 金币`; }
    return price > 0 ? `${fmtInt(price)} 金币 · 还差 ${fmtInt(short)} 金币` : `还差 ${fmtInt(short)} 金币`;
  }
  return `${fmtInt(price)} 金币`;
}

/**
 * 由纯数据生成一行升级行。
 * 副标题 = 价格文案 (+ "· 每分钟 +X")；徽标 = " +gainPct%"（可被入参覆盖）。
 */
export function blockUpgradeRow(input: BlockUpgradeInput): BlockUpgradeRow {
  const kind = input.kind;
  const price = nonNegInt(input.priceCoins);
  const short = nonNegInt(input.shortfallCoins);
  const priceText = upgradePriceText(kind, price, short);
  const title = input.levelText ? `${input.title} ${input.levelText}` : input.title;
  const delta = input.deltaText !== undefined
    ? input.deltaText
    : (nonNegInt(input.deltaMilliPerMin) > 0 ? `每分钟 +${fmtRateMilli2(nonNegInt(input.deltaMilliPerMin))}` : '');
  const subtitle = delta ? `${priceText} · ${delta}` : priceText;
  const badge = input.badge !== undefined ? input.badge : (input.gainPct ? `+${input.gainPct}%` : undefined);
  const actionable = kind === 'ok' || kind === 'poor';
  return {
    id: input.id,
    type: 'upgrade',
    kind,
    title,
    subtitle,
    badge,
    disabled: input.disabled !== undefined ? input.disabled : !actionable,
    actionable,
    priceText,
  };
}

/** 市政厅（议事厅）升级行的入参。 */
export interface BlockHallInput {
  readonly id?: string;
  readonly title?: string;
  /** 当前等级。 */
  readonly level: number;
  /** 等级上限（给了就显示 "Lv 3/10000"）。 */
  readonly maxLevel?: number;
  /** 0.1 冻结的市政厅升级价（金币）。 */
  readonly upgradeCostCoins: number;
  /** 还差多少金币（>0 = 金币不足）。 */
  readonly shortfallCoins?: number;
  /** 离线结算挂起。 */
  readonly pending?: boolean;
}

/** 市政厅升级行：由「冻结升级价 + 满级标记 + 缺口」推导 kind。 */
export function blockHallRow(input: BlockHallInput): BlockUpgradeRow {
  const level = Math.max(0, Math.floor(finite(input.level, 0)));
  const maxLevel = input.maxLevel !== undefined ? Math.max(0, Math.floor(finite(input.maxLevel, 0))) : undefined;
  const cost = nonNegInt(input.upgradeCostCoins);
  const short = nonNegInt(input.shortfallCoins);
  const atMax = maxLevel !== undefined && maxLevel > 0 && level >= maxLevel;
  const kind: BlockRowKind = input.pending ? 'pending'
    : atMax ? 'max'
      : short > 0 ? 'poor'
        : cost <= 0 ? 'none'
          : 'ok';
  const levelText = maxLevel !== undefined && maxLevel > 0 && !atMax ? `Lv ${level}/${maxLevel}` : `Lv ${level}`;
  return blockUpgradeRow({
    id: input.id ?? BLOCK_HALL_ROW_ID,
    title: input.title ?? '市政厅',
    levelText,
    kind,
    priceCoins: cost,
    shortfallCoins: short,
  });
}

/** 区（城区）升级行的入参（字段与 session.districtRow() 对齐）。 */
export interface BlockDistrictInput {
  readonly id?: string;
  readonly title?: string;
  /** 当前区等级。 */
  readonly level: number;
  /** 等级上限（给了就显示 "Lv 3/10000"）。 */
  readonly maxLevel?: number;
  /** 当前全城产速增益百分比（每级 +6）。 */
  readonly gainPct?: number;
  /** 下一级费用（金币）。 */
  readonly nextCostCoins: number;
  /** 还差多少金币。 */
  readonly shortfallCoins: number;
  /** DistrictRow.state（'ok' | 'poor' | 'max' | 'pending'，是 BlockRowKind 的子集）。 */
  readonly state: 'ok' | 'poor' | 'max' | 'pending';
}

/** 区（城区）升级行：kind 直接取 DistrictRow.state（同一套词汇）。 */
export function blockDistrictRow(input: BlockDistrictInput): BlockUpgradeRow {
  const level = Math.max(0, Math.floor(finite(input.level, 0)));
  const maxLevel = input.maxLevel !== undefined ? Math.max(0, Math.floor(finite(input.maxLevel, 0))) : undefined;
  const kind: BlockRowKind = input.state;
  const atMax = kind === 'max';
  const levelText = maxLevel !== undefined && maxLevel > 0 && !atMax ? `Lv ${level}/${maxLevel}` : `Lv ${level}`;
  const gain = finite(input.gainPct, 0);
  return blockUpgradeRow({
    id: input.id ?? BLOCK_DISTRICT_ROW_ID,
    title: input.title ?? '城区',
    levelText,
    kind,
    priceCoins: nonNegInt(input.nextCostCoins),
    shortfallCoins: nonNegInt(input.shortfallCoins),
    gainPct: gain > 0 ? String(gain) : undefined,
  });
}

/* ================================== 行模型装配 ================================== */

/**
 * 街区 tab 的行（固定顺序：目标提示 → 市政厅 → 区）。
 * 目标提示行 id 恒为 'goal'；升级行的 id 由入参给（缺省 'hall' / 'district'）。
 */
export function blockTabRows(input: BlockTabInput): BlockTabModel {
  const rows: BlockTabRow[] = [];
  const goal = input.goal ? blockGoalRow(input.goal) : null;
  if (goal) { rows.push(goal); }
  if (input.hall) { rows.push(blockUpgradeRow(input.hall)); }
  if (input.district) { rows.push(blockUpgradeRow(input.district)); }
  return { rows, goal, emptyText: BLOCK_TAB_EMPTY_TEXT };
}

/* ================================== 纯布局函数 ================================== */

/** 街区 tab 的排版入参。 */
export interface BlockTabLayoutInput {
  /** 内容区（行矩形不得越出它）。 */
  readonly content: TabContentRect;
  /** 目标提示行高（缺省 22）。 */
  readonly goalH?: number;
  /** 升级行高（缺省 56）。 */
  readonly rowH?: number;
  /** 行间距（缺省 8）。 */
  readonly gap?: number;
  /** 左右内边距（缺省 12）。 */
  readonly padX?: number;
}

/** 街区 tab 的排版结果。 */
export interface BlockTabLayout {
  /** 规整后的内容区。 */
  readonly content: TabContentRect;
  /** 目标提示行矩形（没有目标提示则为 null）。 */
  readonly goalRect: TabRect | null;
  /** 升级行矩形（与 model.rows 里的升级行一一对应、顺序相同）。 */
  readonly rowRects: ReadonlyArray<TabRect>;
  /** 命中矩形（顺序 = 视觉顺序；目标提示行 interactive=false）。 */
  readonly hits: ReadonlyArray<TabRowHit>;
  /** true = 有行放不下（内容区太矮）。 */
  readonly overflow: boolean;
}

/**
 * 纯布局：把街区 tab 的行摆进内容区，返回每行矩形与命中矩形。
 * 保证：① 所有矩形都在 content 内；② 数值有限、无 NaN；
 * ③ 行数恒定（= 模型行数），放不下的行**高度夹到剩余空间**（可能是 0）并置 overflow=true，绝不越界。
 */
export function layoutBlockTab(model: BlockTabModel, inp: BlockTabLayoutInput): BlockTabLayout {
  const content = sanitizeRect(inp.content);
  const padX = clamp(finite(inp.padX, BLOCK_ROW_PAD_X), 0, content.w / 2);
  const gap = Math.max(0, finite(inp.gap, BLOCK_ROW_GAP));
  const goalH = Math.max(0, finite(inp.goalH, BLOCK_GOAL_H));
  const rowH = Math.max(0, finite(inp.rowH, BLOCK_ROW_H));
  const innerX = content.x + padX;
  const innerW = Math.max(0, content.w - padX * 2);
  const bottom = content.y + content.h;

  const hits: TabRowHit[] = [];
  const rowRects: TabRect[] = [];
  let goalRect: TabRect | null = null;
  let overflow = false;
  let cursor = content.y;

  const goal = model.goal ?? model.rows.find((r) => r.type === 'goal') ?? null;
  if (goal) {
    const y = Math.min(Math.max(cursor, content.y), bottom);
    const h = Math.max(0, Math.min(goalH, bottom - y));
    goalRect = { x: innerX, y, w: innerW, h };
    hits.push({ id: goal.id, rect: goalRect, interactive: false });
    if (h < goalH - 1e-6) { overflow = true; }
    cursor = y + goalH + gap;
  }

  for (const row of model.rows) {
    if (row.type !== 'upgrade') { continue; }
    const y = Math.min(Math.max(cursor, content.y), bottom);
    const h = Math.max(0, Math.min(rowH, bottom - y));
    const rect: TabRect = { x: innerX, y, w: innerW, h };
    rowRects.push(rect);
    hits.push({ id: row.id, rect, interactive: row.actionable });
    if (h < rowH - 1e-6) { overflow = true; }
    cursor = y + rowH + gap;
  }

  return { content, goalRect, rowRects, hits, overflow };
}

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

/** 有限数兜底（非有限 → fallback）。 */
function finite(v: unknown, fallback: number): number {
  return typeof v === 'number' && Number.isFinite(v) ? v : fallback;
}

/** 非负整数（金币 / 计数）。 */
function nonNegInt(v: unknown): number {
  return Math.max(0, Math.floor(finite(v, 0)));
}

/** 数值夹取。 */
function clamp(v: number, lo: number, hi: number): number {
  if (hi < lo) { return lo; }
  return Math.min(hi, Math.max(lo, v));
}

/** 矩形规整（有限、宽高非负）。 */
function sanitizeRect(r: TabContentRect): TabContentRect {
  return {
    x: finite(r?.x, 0),
    y: finite(r?.y, 0),
    w: Math.max(0, finite(r?.w, 0)),
    h: Math.max(0, finite(r?.h, 0)),
  };
}
