/**
 * S-24 · 其他 tab（more）· 视图模型 + 纯布局函数。
 * -----------------------------------------------------------------------------
 * 契约：`docs/S-24-抽屉契约.md` §4 —— `moreTabRows(input)` → **报告 / 设置 / 说明**三行（固定顺序）。
 *
 * 硬边界（勿越界）：
 *  · 不画 canvas、不碰 DOM、不 import three；
 *  · 不 import `src/ui/hud.ts`、不 import `src/game/session.ts`；
 *  · 只做「行数据 / 排序 / 命中矩形」，不做任何经济计算。
 *
 * **调试入口仅内部包可见**：
 *  入参 `internal` 为 true 时**追加**一行调试入口（id 恒为 `'debug'`），为 false 时**绝不出现**该行。
 *  正式包由调用方恒传 `false`（本文件不引用 `__INTERNAL__`，也不含任何调试事件名 / 正式包禁用词）。
 *
 * 公共行模型（`TabRowModel` / `TabListModel` / `TabRect` / `TabHitRect`）统一来自 `src/ui/tabs/tabs-common.ts`
 * （S2 维护的唯一权威来源），本文件只**再导出**、不重复定义。
 */

import type { TabRect, TabRowModel, TabListModel, TabHitRect } from './tabs-common';
// @ts-expect-error TS5097：仓库 tsconfig 未开 `allowImportingTsExtensions`；显式写 `.ts` 扩展名，
// 使本模块能被 Node 24 直接 import（类型剥离），esbuild 打包同样可解析（已实测）。
import { tabRowRects, TAB_LIST_ROW_H, TAB_LIST_ROW_GAP } from './tabs-common.ts';

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

/* ================================== 行模型 ================================== */

/** 报告行 id。 */
export const MORE_ROW_REPORT = 'report';
/** 设置行 id。 */
export const MORE_ROW_SETTINGS = 'settings';
/** 说明行 id。 */
export const MORE_ROW_HELP = 'help';
/** 调试入口行 id（**仅内部包**）。 */
export const MORE_ROW_DEBUG = 'debug';

/** 行类别。 */
export type MoreTabRowType = 'report' | 'settings' | 'help' | 'debug';

/** 其他 tab 的一行。 */
export interface MoreTabRow extends TabRowModel {
  readonly type: MoreTabRowType;
  /** 是否可点（三行 + 调试行都可点）。 */
  readonly actionable: boolean;
}

/** 其他 tab 的视图模型。 */
export interface MoreTabModel extends TabListModel {
  readonly rows: ReadonlyArray<MoreTabRow>;
}

/** `moreTabRows` 的入参（全部纯数据）。 */
export interface MoreTabInput {
  /**
   * 是否内部包。
   * true → 追加一行调试入口（id = 'debug'，排在最后）；
   * false → **不出现**调试行（正式包恒 false）。
   */
  readonly internal: boolean;
  /** 报告行副标题（可覆盖默认文案）。 */
  readonly reportSubtitle?: string;
  /** 设置行副标题（可覆盖默认文案）。 */
  readonly settingsSubtitle?: string;
  /** 说明行副标题（可覆盖默认文案）。 */
  readonly helpSubtitle?: string;
  /** 调试行副标题（可覆盖默认文案）。 */
  readonly debugSubtitle?: string;
}

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

/** 行高（与公共常量 `TAB_LIST_ROW_H` 一致，抽屉内各 tab 行高统一）。 */
export const MORE_ROW_H = TAB_LIST_ROW_H;
/** 行间距（与公共常量 `TAB_LIST_ROW_GAP` 一致）。 */
export const MORE_ROW_GAP = TAB_LIST_ROW_GAP;
/** 内容区左右内边距（S1 的 `content` 是整屏宽，故这里内缩 12px）。 */
export const MORE_ROW_PAD_X = 12;
/** 空列表文案（本 tab 恒有行，保留字段以符合契约 §4 的 TabListModel 形状）。 */
export const MORE_TAB_EMPTY_TEXT = '暂无可用入口';

/* ================================== 行装配 ================================== */

/** 各行默认副标题（键 = 行类别）。 */
const DEFAULT_SUBS: Readonly<Record<MoreTabRowType, string>> = {
  report: '本次经营报告',
  settings: '设置与选项',
  help: '玩法说明',
  debug: '内部调试面板',
};

/**
 * 其他 tab 的行（**固定顺序**：报告 → 设置 → 说明 →〔内部包〕调试）。
 * `internal === false` 时**一定**不含调试行。
 */
export function moreTabRows(input: MoreTabInput): MoreTabModel {
  const rows: MoreTabRow[] = [
    { id: MORE_ROW_REPORT, type: 'report', title: '报告', subtitle: input.reportSubtitle ?? DEFAULT_SUBS.report, actionable: true },
    { id: MORE_ROW_SETTINGS, type: 'settings', title: '设置', subtitle: input.settingsSubtitle ?? DEFAULT_SUBS.settings, actionable: true },
    { id: MORE_ROW_HELP, type: 'help', title: '说明', subtitle: input.helpSubtitle ?? DEFAULT_SUBS.help, actionable: true },
  ];
  if (input.internal === true) {
    rows.push({ id: MORE_ROW_DEBUG, type: 'debug', title: '调试', subtitle: input.debugSubtitle ?? DEFAULT_SUBS.debug, actionable: true });
  }
  return { rows, emptyText: MORE_TAB_EMPTY_TEXT };
}

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

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

/** 其他 tab 的排版入参。 */
export interface MoreTabLayoutInput {
  /** 内容区（行矩形不得越出它）。 */
  readonly content: TabRect;
  /** 行高（缺省 = 公共常量 `TAB_LIST_ROW_H` = 44）。 */
  readonly rowH?: number;
  /** 行间距（缺省 = 公共常量 `TAB_LIST_ROW_GAP` = 4）。 */
  readonly gap?: number;
  /** 左右内边距（缺省 12）。 */
  readonly padX?: number;
}

/** 其他 tab 的排版结果。 */
export interface MoreTabLayout {
  /** 规整后的内容区。 */
  readonly content: TabRect;
  /** 行矩形（与 model.rows 一一对应、顺序相同）。 */
  readonly rowRects: ReadonlyArray<TabRect>;
  /** 命中矩形（顺序 = 视觉顺序）。 */
  readonly hits: ReadonlyArray<MoreTabHit>;
  /** true = 有行放不下（内容区太矮）。 */
  readonly overflow: boolean;
}

/**
 * 纯布局：把其他 tab 的行摆进内容区，返回每行矩形与命中矩形。
 * 几何复用公共的 `tabRowRects`（与土地 / 居民 tab 同一套行距）。
 * 保证：① 所有矩形都在 content 内；② 数值有限、无 NaN；
 * ③ 行数恒定（= 模型行数），放不下的行**高度夹到剩余空间**（可能是 0）并置 overflow=true，绝不越界。
 */
export function layoutMoreTab(model: MoreTabModel, inp: MoreTabLayoutInput): MoreTabLayout {
  const content = sanitizeRect(inp.content);
  const padX = clamp(finite(inp.padX, MORE_ROW_PAD_X), 0, content.w / 2);
  const gap = Math.max(0, finite(inp.gap, MORE_ROW_GAP));
  const rowH = Math.max(0, finite(inp.rowH, MORE_ROW_H));
  const inner: TabRect = {
    x: content.x + padX,
    y: content.y,
    w: Math.max(0, content.w - padX * 2),
    h: content.h,
  };

  const ids = model.rows.map((r) => r.id);
  const rects = tabRowRects(inner, model.rows.length, { rowH, gap, ids });

  const rowRects: TabRect[] = [];
  const hits: MoreTabHit[] = [];
  let overflow = false;
  for (let i = 0; i < model.rows.length; i++) {
    const row = model.rows[i];
    const rect = rects[i].rect;
    rowRects.push(rect);
    hits.push({ id: row.id, rect, interactive: row.actionable });
    if (rect.h < rowH - 1e-6) { overflow = true; }
  }

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

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

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

/** 数值夹取。 */
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: TabRect): TabRect {
  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)),
  };
}
