import React from "react";
import { fmtClock, fmtDate } from "./time";
import { LoadingTitle } from "./loading-indicator";
import { MarkdownBody } from "./markdown";
import { errorMessage, isUniDeskRequestError, requestJson } from "./unidesk-error";
import { UniDeskErrorBanner } from "./unidesk-error-banner";

type AnyRecord = Record<string, any>;

const h = React.createElement;
const { useEffect } = React;
const useState: any = React.useState;

const recordTypes = ["all", "meeting", "decision", "goal", "blocker", "debt", "experiment"];
const recordLevels = ["all", "G0", "G1", "G2", "G3", "P0", "P1", "P2", "P3", "none"];
const recordStatuses = ["all", "active", "blocked", "parked", "done"];
const diaryWeekdays = ["一", "二", "三", "四", "五", "六", "日"];

export const DOC_TYPE_CODES = ["DCSN", "GOAL", "PLAN", "RPRT", "ACTN", "ISSU", "RETR", "RQST", "RESP", "MINS"] as const;
export type DocTypeCode = typeof DOC_TYPE_CODES[number];

export const docTypeLabels: Record<DocTypeCode, string> = {
  DCSN: "决策/决议",
  GOAL: "目标",
  PLAN: "计划",
  RPRT: "报告",
  ACTN: "行动",
  ISSU: "问题",
  RETR: "复盘",
  RQST: "请示",
  RESP: "批复/答复",
  MINS: "会议纪要",
};

const docTypeOrder: DocTypeCode[] = ["DCSN", "GOAL", "PLAN", "RPRT", "ACTN", "ISSU", "RETR", "RQST", "RESP", "MINS"];
const docTypeAliases: Record<string, DocTypeCode> = {
  DECISION: "DCSN",
  DECISIONS: "DCSN",
  GOALS: "GOAL",
  PLANS: "PLAN",
  REPORT: "RPRT",
  REPORTS: "RPRT",
  ACTION: "ACTN",
  ACTIONS: "ACTN",
  ISSUE: "ISSU",
  ISSUES: "ISSU",
  RETROSPECTIVE: "RETR",
  RETROSPECTIVES: "RETR",
  RETRO: "RETR",
  REQUEST: "RQST",
  REQUESTS: "RQST",
  RESPONSE: "RESP",
  RESPONSES: "RESP",
  REPLY: "RESP",
  MINUTES: "MINS",
  MEETINGMINUTES: "MINS",
};
const DOC_NO_CORE_PATTERN = "DC[-−–—]([A-Z]{2,5})[-−–—]([A-Z][0-9])[-−–—](\\d{4})[-−–—](\\d{1,6})";
const DOC_NO_PATTERN = new RegExp(`\\b${DOC_NO_CORE_PATTERN}\\b`, "iu");
const DOC_NO_PREFIX_PATTERN = new RegExp(`^\\s*(?:#+\\s*)?${DOC_NO_CORE_PATTERN}(?=\\s|[:：,，.;；/\\\\]|$)`, "iu");

export interface DocMetadata {
  docNo: string;
  docType: DocTypeCode | "";
  docTypeLabel: string;
  priority: string;
  year: string;
  sequence: string;
}

interface ParsedDocNo {
  docNo: string;
  docType: DocTypeCode;
  priority: string;
  year: string;
  sequence: string;
}
const requirementViews = [
  { id: "all", label: "全部需求" },
  { id: "external-goal", label: "外部目标" },
  { id: "internal-goal", label: "内部目标" },
  { id: "blocker", label: "阻塞" },
  { id: "parked", label: "停放事项" },
  { id: "authority", label: "决议/实验/债务" },
];
const recordCategories = [
  { id: "external-goal", label: "外部目标", type: "goal", level: "G0", status: "active", tags: ["external-goal", "requirement"] },
  { id: "internal-goal", label: "内部目标", type: "goal", level: "G1", status: "active", tags: ["internal-goal", "requirement"] },
  { id: "blocker", label: "阻塞", type: "blocker", level: "P0", status: "blocked", tags: ["blocker", "requirement"] },
  { id: "parked", label: "停放事项", type: "goal", level: "G3", status: "parked", tags: ["parked", "requirement"] },
  { id: "decision", label: "决议", type: "decision", level: "none", status: "active", tags: ["decision"] },
  { id: "experiment", label: "实验", type: "experiment", level: "G2", status: "active", tags: ["experiment"] },
  { id: "debt", label: "债务", type: "debt", level: "P2", status: "active", tags: ["debt"] },
];
const defaultDiarySourceFile = "frontend-work-diary.md";

function StatusBadge({ status, children }: AnyRecord) {
  const normalized = String(status || "unknown").toLowerCase();
  return h("span", { className: `status-badge ${normalized}` }, children || status || "unknown");
}

function MetricCard({ label, value, hint, tone }: AnyRecord) {
  return h("article", { className: `metric-card ${tone || ""}` },
    h("div", { className: "metric-label" }, label),
    h("div", { className: "metric-value" }, value),
    h("div", { className: "metric-hint" }, hint),
  );
}

function Panel({ title, eyebrow, actions, children, className, loading }: AnyRecord) {
  return h("section", { className: `panel ${className || ""}` },
    h("div", { className: "panel-head" },
      h("div", null,
        eyebrow ? h("p", { className: "panel-eyebrow" }, eyebrow) : null,
        h(LoadingTitle, { title, loading }),
      ),
      actions ? h("div", { className: "panel-actions" }, actions) : null,
    ),
    h("div", { className: "panel-body" }, children),
  );
}

function RawButton({ title, data, onOpen, testId }: AnyRecord) {
  return h("button", {
    type: "button",
    className: "ghost-btn",
    "data-testid": testId,
    onClick: () => onOpen(title, data),
  }, "查看原始JSON");
}

function EmptyState({ title, text }: AnyRecord) {
  return h("div", { className: "empty-state" }, h("strong", null, title), h("span", null, text));
}

function microserviceRuntime(service: any): AnyRecord {
  return service?.runtime && typeof service.runtime === "object" && !Array.isArray(service.runtime) ? service.runtime : {};
}

function microserviceBackend(service: any): AnyRecord {
  return service?.backend && typeof service.backend === "object" && !Array.isArray(service.backend) ? service.backend : {};
}

function microserviceRepository(service: any): AnyRecord {
  return service?.repository && typeof service.repository === "object" && !Array.isArray(service.repository) ? service.repository : {};
}

function decisionApi(apiBaseUrl: string, path: string): string {
  return `${apiBaseUrl}/microservices/decision-center/proxy${path}`;
}

function levelTone(level: string): string {
  if (level === "G0" || level === "G1") return "online";
  if (level === "P0" || level === "P1") return "failed";
  if (level === "none") return "unknown";
  return "warn";
}

function statusTone(status: string): string {
  if (status === "done") return "online";
  if (status === "blocked") return "failed";
  if (status === "parked") return "warn";
  return "unknown";
}

function browserDateOnly(value = new Date()): string {
  const year = value.getFullYear();
  const month = String(value.getMonth() + 1).padStart(2, "0");
  const day = String(value.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function monthFromDate(value: string): string {
  return /^\d{4}-\d{2}-\d{2}$/u.test(value) ? value.slice(0, 7) : browserDateOnly().slice(0, 7);
}

function monthStartDate(month: string): Date | null {
  if (!/^\d{4}-\d{2}$/u.test(month)) return null;
  const [year, monthIndex] = month.split("-").map(Number);
  const date = new Date(year || 0, (monthIndex || 1) - 1, 1);
  return Number.isNaN(date.getTime()) ? null : date;
}

function monthDateGrid(month: string): string[] {
  const start = monthStartDate(month);
  if (start === null) return [];
  const daysInMonth = new Date(start.getFullYear(), start.getMonth() + 1, 0).getDate();
  const mondayOffset = (start.getDay() + 6) % 7;
  const cells: string[] = [];
  for (let index = 0; index < mondayOffset; index += 1) cells.push("");
  for (let day = 1; day <= daysInMonth; day += 1) {
    cells.push(`${month}-${String(day).padStart(2, "0")}`);
  }
  while (cells.length % 7 !== 0) cells.push("");
  return cells;
}

function recordStringArray(record: any, keys: string[]): string[] {
  for (const key of keys) {
    const value = record?.[key];
    if (Array.isArray(value)) return value.map((item) => String(item || "").trim()).filter(Boolean);
    if (typeof value === "string" && value.trim()) return parseCsv(value);
  }
  return [];
}

function recordStringField(record: any, keys: string[]): string {
  for (const key of keys) {
    const value = record?.[key];
    if (value !== null && value !== undefined && String(value).trim()) return String(value).trim();
  }
  return "";
}

function recordTags(record: any): string[] {
  return Array.isArray(record?.tags) ? record.tags.map((tag: any) => String(tag || "").trim()).filter(Boolean) : parseCsv(record?.tags);
}

function recordTagValues(record: any, prefix: string): string[] {
  const marker = `${prefix}:`;
  return recordTags(record)
    .filter((tag) => tag.toLowerCase().startsWith(marker.toLowerCase()))
    .map((tag) => tag.slice(marker.length).trim())
    .filter(Boolean);
}

function firstRecordTagValue(record: any, prefix: string): string {
  return recordTagValues(record, prefix)[0] || "";
}

function recordSource(record: any): string {
  return recordStringField(record, ["source", "sourceLabel", "sourceFile"]) || firstRecordTagValue(record, "source") || recordStringField(record, ["sourceSession"]) || "--";
}

function recordIssueTaskLabel(record: any): string {
  const issue = recordStringField(record, ["issueId", "issue", "githubIssue", "githubIssueId", "externalIssue"]) || firstRecordTagValue(record, "issue");
  const task = recordStringField(record, ["taskId", "task"]);
  if (issue && task) return `issue:${issue} / task:${task}`;
  if (issue) return `issue:${issue}`;
  if (task) return `task:${task}`;
  return "";
}

function fmtRecordTime(value: any): string {
  return fmtDate(value) || "--";
}

function shortText(value: any, max = 220): string {
  const text = String(value || "").replace(/\s+/gu, " ").trim();
  return text.length > max ? `${text.slice(0, max - 1)}...` : text;
}

function stableTestId(value: any): string {
  return String(value || "").replace(/[^A-Za-z0-9_-]+/g, "-") || "item";
}

function parseCsv(value: any): string[] {
  return String(value || "")
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean)
    .slice(0, 50);
}

function tagsText(value: any): string {
  return Array.isArray(value) ? value.join(", ") : String(value || "");
}

function normalizeDocToken(value: any): string {
  return String(value || "").trim().toUpperCase();
}

function normalizeDocType(value: any): DocTypeCode | "" {
  const token = normalizeDocToken(value).replace(/[^A-Z0-9]+/gu, "");
  if (DOC_TYPE_CODES.includes(token as DocTypeCode)) return token as DocTypeCode;
  return docTypeAliases[token] || "";
}

function normalizePriority(value: any): string {
  const match = normalizeDocToken(value).match(/\b([PG][0-3])\b/u);
  return match?.[1] || "";
}

function normalizeYear(value: any): string {
  const match = String(value || "").match(/\b(20\d{2}|19\d{2})\b/u);
  return match?.[1] || "";
}

function normalizeSequence(value: any): string {
  const match = String(value || "").trim().match(/^\D*(\d{1,6})\D*$/u);
  if (!match) return "";
  return match[1].padStart(3, "0");
}

function parseDocNo(value: any): ParsedDocNo | null {
  const match = String(value || "").match(DOC_NO_PATTERN);
  if (!match) return null;
  const docType = normalizeDocType(match[1]);
  const priority = normalizePriority(match[2]);
  const year = normalizeYear(match[3]);
  const sequence = normalizeSequence(match[4]);
  if (!docType || !priority || !year || !sequence) return null;
  return {
    docNo: `DC-${docType}-${priority}-${year}-${sequence}`,
    docType,
    priority,
    year,
    sequence,
  };
}

function parseDocNoPrefix(value: any): ParsedDocNo | null {
  const match = String(value || "").match(DOC_NO_PREFIX_PATTERN);
  return match ? parseDocNo(match[0]) : null;
}

function firstBodyWindow(record: any): string {
  const body = recordStringField(record, ["body", "content", "markdown", "summary"]);
  if (!body) return "";
  const lines = body.split(/\r?\n/u).slice(0, 8).join("\n");
  const paragraphs = body.split(/\r?\n\s*\r?\n/u).slice(0, 2).join("\n\n");
  return `${lines}\n${paragraphs}`.slice(0, 1600);
}

function mergeParsedDocNo(metadata: DocMetadata, parsed: ParsedDocNo | null): void {
  if (!parsed) return;
  if (!metadata.docNo) metadata.docNo = parsed.docNo;
  if (!metadata.docType) metadata.docType = parsed.docType;
  if (!metadata.priority) metadata.priority = parsed.priority;
  if (!metadata.year) metadata.year = parsed.year;
  if (!metadata.sequence) metadata.sequence = parsed.sequence;
}

function completeDocNoFromParts(metadata: DocMetadata): string {
  return metadata.docType && metadata.priority && metadata.year && metadata.sequence
    ? `DC-${metadata.docType}-${metadata.priority}-${metadata.year}-${metadata.sequence}`
    : "";
}

export function extractDocMetadata(record: any): DocMetadata {
  const metadata: DocMetadata = {
    docNo: "",
    docType: "",
    docTypeLabel: "",
    priority: "",
    year: "",
    sequence: "",
  };

  mergeParsedDocNo(metadata, parseDocNo(recordStringField(record, ["docNo", "documentNo", "documentNumber", "documentId"])));
  const structuredDocType = normalizeDocType(recordStringField(record, ["docType", "documentType", "documentKind"]));
  const structuredPriority = normalizePriority(recordStringField(record, ["priority", "docPriority", "documentPriority"]));
  const structuredYear = normalizeYear(recordStringField(record, ["year", "docYear", "documentYear"]));
  const structuredSequence = normalizeSequence(recordStringField(record, ["sequence", "seq", "docSequence", "documentSequence"]));
  if (structuredDocType) metadata.docType = structuredDocType;
  if (structuredPriority) metadata.priority = structuredPriority;
  if (structuredYear) metadata.year = structuredYear;
  if (structuredSequence) metadata.sequence = structuredSequence;

  const docNoFromParts = completeDocNoFromParts(metadata);
  if (!metadata.docNo && docNoFromParts) metadata.docNo = docNoFromParts;

  mergeParsedDocNo(metadata, parseDocNoPrefix(record?.title));
  mergeParsedDocNo(metadata, parseDocNo(recordStringField(record, ["title", "name"])));

  for (const tagValue of recordTagValues(record, "doc-no")) mergeParsedDocNo(metadata, parseDocNo(tagValue));
  if (!metadata.docType) metadata.docType = normalizeDocType(firstRecordTagValue(record, "doc-type"));
  if (!metadata.priority) metadata.priority = normalizePriority(firstRecordTagValue(record, "doc-priority"));
  if (!metadata.year) metadata.year = normalizeYear(firstRecordTagValue(record, "doc-year"));
  if (!metadata.sequence) metadata.sequence = normalizeSequence(firstRecordTagValue(record, "doc-sequence"));

  const tagDocNoFromParts = completeDocNoFromParts(metadata);
  if (!metadata.docNo && tagDocNoFromParts) metadata.docNo = tagDocNoFromParts;

  mergeParsedDocNo(metadata, parseDocNo(firstBodyWindow(record)));

  const finalDocNoFromParts = completeDocNoFromParts(metadata);
  if (!metadata.docNo && finalDocNoFromParts) metadata.docNo = finalDocNoFromParts;
  metadata.docTypeLabel = metadata.docType ? docTypeLabels[metadata.docType] : "";
  return metadata;
}

export function extractDocNo(record: any): string {
  return extractDocMetadata(record).docNo;
}

export function buildDocTypeTree(records: any[]): Array<{ type: DocTypeCode; label: string; nodes: any[] }> {
  const byType = new Map<DocTypeCode, any[]>();
  for (const code of docTypeOrder) byType.set(code, []);
  for (const record of records) {
    const code = extractDocMetadata(record).docType || "DCSN";
    byType.get(code)!.push(record);
  }
  return docTypeOrder
    .map((code) => ({ type: code, label: docTypeLabels[code], nodes: byType.get(code) || [] }))
    .filter((group) => group.nodes.length > 0);
}

function buildTagGroups(records: any[]): Array<{ tag: string; nodes: any[] }> {
  const tagCounts = new Map<string, any[]>();
  const priorityTags = ["thesis", "external-demand", "D518"];
  for (const record of records) {
    const tags = Array.isArray(record?.tags) ? record.tags : [];
    const labelTags = tags.filter((t: string) => {
      const lower = String(t || "").toLowerCase();
      return priorityTags.some((p) => lower.includes(p)) || /^doc-type:/.test(lower);
    });
    if (labelTags.length === 0) labelTags.push("未分类");
    for (const tag of labelTags) {
      const bucket = tagCounts.get(String(tag)) || [];
      bucket.push(record);
      tagCounts.set(String(tag), bucket);
    }
  }
  return [...tagCounts.entries()]
    .map(([tag, nodes]) => ({ tag, nodes }))
    .sort((a, b) => {
      const ai = priorityTags.findIndex((p) => a.tag.toLowerCase().includes(p));
      const bi = priorityTags.findIndex((p) => b.tag.toLowerCase().includes(p));
      if (ai !== bi) return (ai === -1 ? 99 : ai) - (bi === -1 ? 99 : bi);
      return a.tag.localeCompare(b.tag);
    });
}

function DocTreeNode({ record, depth, onSelect, selectedId }: AnyRecord) {
  const metadata = extractDocMetadata(record);
  const label = metadata.docNo ? `${metadata.docNo} ${record.title || ""}` : (record.title || record.id || "--");
  return h("div", { className: `doc-tree-node depth-${Math.min(depth, 3)}` },
    h("button", {
      type: "button",
      className: `doc-tree-item ${selectedId === record.id ? "selected" : ""}`,
      onClick: () => onSelect(record),
      "data-testid": `doc-tree-item-${stableTestId(record.id)}`,
    },
      h("span", { className: "doc-tree-meta" }, metadata.docType || record.type || "--"),
      h("span", { className: "doc-tree-label" }, shortText(label, 80)),
    ),
  );
}

function DocTreeGroup({ group, onSelect, selectedId, defaultOpen }: AnyRecord) {
  const [open, setOpen] = useState(defaultOpen !== false);
  return h("div", { className: "doc-tree-group", "data-testid": `doc-tree-group-${group.type}` },
    h("button", {
      type: "button",
      className: `doc-tree-group-head ${open ? "open" : ""}`,
      onClick: () => setOpen((v: any) => !v),
      "data-testid": `doc-tree-group-toggle-${group.type}`,
    },
      h("span", { className: "doc-tree-group-label" }, group.label),
      h("span", { className: "doc-tree-group-count" }, group.nodes.length),
      h("span", { className: "doc-tree-caret" }, open ? "▾" : "▸"),
    ),
    open ? h("div", { className: "doc-tree-group-body" },
      group.nodes.map((record: any) => h(DocTreeNode, { key: record.id, record, depth: 0, onSelect, selectedId })),
    ) : null,
  );
}

function TagTreeGroup({ group, onSelect, selectedId, defaultOpen }: AnyRecord) {
  const [open, setOpen] = useState(defaultOpen !== false);
  return h("div", { className: "doc-tree-group", "data-testid": `tag-tree-group-${stableTestId(group.tag)}` },
    h("button", {
      type: "button",
      className: `doc-tree-group-head ${open ? "open" : ""}`,
      onClick: () => setOpen((v: any) => !v),
      "data-testid": `tag-tree-group-toggle-${stableTestId(group.tag)}`,
    },
      h("span", { className: "doc-tree-group-label" }, group.tag),
      h("span", { className: "doc-tree-group-count" }, group.nodes.length),
      h("span", { className: "doc-tree-caret" }, open ? "▾" : "▸"),
    ),
    open ? h("div", { className: "doc-tree-group-body" },
      group.nodes.map((record: any) => h(DocTreeNode, { key: record.id, record, depth: 0, onSelect, selectedId })),
    ) : null,
  );
}

function DocTypeTree({ records, onSelect, selectedId, activeGrouping }: AnyRecord) {
  if (!records.length) return h(EmptyState, { title: "暂无文书", text: "通过 CLI 上传文书后会显示在目录树中。" });
  const groups = activeGrouping === "type" ? buildDocTypeTree(records) : buildTagGroups(records);
  if (groups.length === 0) return h(EmptyState, { title: "暂无文书", text: "通过 CLI 上传文书后会显示在目录树中。" });
  return h("div", { className: "doc-type-tree", "data-testid": "doc-type-tree" },
    activeGrouping === "type"
      ? groups.map((group: any) => h(DocTreeGroup, { key: group.type, group, onSelect, selectedId }))
      : groups.map((group: any) => h(TagTreeGroup, { key: group.tag, group, onSelect, selectedId })),
  );
}

function DocDetailHeader({ record, onBack }: AnyRecord) {
  const metadata = extractDocMetadata(record);
  return h("div", { className: "doc-detail-header" },
    onBack ? h("button", { type: "button", className: "ghost-btn compact", onClick: onBack, "data-testid": "doc-detail-back" }, "← 返回") : null,
    metadata.docNo ? h("span", { className: "doc-detail-docno", "data-testid": "doc-detail-docno" }, metadata.docNo) : null,
    h("h2", { className: "doc-detail-title" }, record.title || "--"),
    h("div", { className: "doc-detail-meta" },
      h("span", null, metadata.docType ? `${metadata.docType} ${metadata.docTypeLabel}` : record.type || "--"),
      h(StatusBadge, { status: levelTone(metadata.priority || record.level) }, metadata.priority || record.level || "none"),
      h(StatusBadge, { status: statusTone(record.status) }, record.status || "--"),
      h("span", { className: "muted" }, `更新 ${fmtRecordTime(record.updatedAt)}`),
    ),
    record.source ? h("a", { href: record.source, target: "_blank", rel: "noreferrer", className: "doc-detail-source" }, `来源: ${record.source}`) : null,
    Array.isArray(record.evidenceLinks) && record.evidenceLinks.length > 0
      ? h("div", { className: "doc-detail-evidence" },
          record.evidenceLinks.slice(0, 3).map((link: string) => h("a", { key: link, href: link, target: "_blank", rel: "noreferrer" }, shortText(link, 60))),
        )
      : null,
  );
}

function DocViewer({ record }: AnyRecord) {
  return h("div", { className: "doc-viewer", "data-testid": "doc-viewer" },
    h(MarkdownBody, { markdown: record.body || record.summary || "", className: "doc-full-markdown" }),
  );
}

function DocEditor({ form, saving, onChange, onSubmit }: AnyRecord) {
  return h("form", { className: "doc-editor-form", onSubmit, "data-testid": "doc-editor" },
    h("label", null, "标题",
      h("input", {
        value: form.title || "",
        onChange: (e: any) => onChange("title", e.target.value),
        placeholder: "文书标题",
        "data-testid": "doc-title-input",
      }),
    ),
    h("label", null, "类型",
      h("select", {
        value: form.type || "decision",
        onChange: (e: any) => onChange("type", e.target.value),
        "data-testid": "doc-type-input",
      }, selectOptions(recordTypes.filter((t: string) => t !== "all"))),
    ),
    h("label", null, "优先级",
      h("select", {
        value: form.level || "none",
        onChange: (e: any) => onChange("level", e.target.value),
        "data-testid": "doc-level-input",
      }, selectOptions(recordLevels.filter((l: string) => l !== "all"))),
    ),
    h("label", null, "状态",
      h("select", {
        value: form.status || "active",
        onChange: (e: any) => onChange("status", e.target.value),
        "data-testid": "doc-status-input",
      }, selectOptions(recordStatuses.filter((s: string) => s !== "all"))),
    ),
    h("label", null, "Tags",
      h("input", {
        value: form.tags || "",
        onChange: (e: any) => onChange("tags", e.target.value),
        placeholder: "逗号分隔",
        "data-testid": "doc-tags-input",
      }),
    ),
    h("label", { className: "wide" }, "正文",
      h("textarea", {
        value: form.body || "",
        onChange: (e: any) => onChange("body", e.target.value),
        placeholder: "Markdown 正文",
        "data-testid": "doc-body-editor",
      }),
    ),
    h("div", { className: "dispatch-actions" },
      h("button", {
        type: "submit",
        disabled: saving || !String(form.title || "").trim(),
        "data-testid": "doc-save-button",
      }, saving ? "保存中…" : "保存"),
    ),
  );
}

function DocDetailSidebar({ record, onSelect, onSave, saving, error, saveMsg, onRaw }: AnyRecord) {
  const [mode, setMode] = useState("view");
  const [form, setForm] = useState({});

  function syncForm(rec: any): void {
    setForm(recordFormFromRecord(rec));
  }

  useEffect(() => {
    if (record) syncForm(record);
  }, [record?.id]);

  function changeField(field: string, value: any): void {
    setForm((prev: any) => ({ ...prev, [field]: value }));
  }

  async function handleSubmit(e: any): Promise<void> {
    e.preventDefault();
    await onSave(form);
  }

  if (!record) {
    return h("div", { className: "doc-sidebar empty", "data-testid": "doc-sidebar-empty" },
      h(EmptyState, { title: "未选择文书", text: "从左侧目录树或列表选择文书查看全文。" }),
    );
  }

  return h("div", { className: "doc-sidebar", "data-testid": "doc-sidebar" },
    h("div", { className: "doc-sidebar-head" },
      h("div", { className: "doc-sidebar-mode-tabs", role: "tablist" },
        h("button", {
          type: "button",
          className: mode === "view" ? "active" : "",
          onClick: () => { setMode("view"); if (record) syncForm(record); },
          "data-testid": "doc-mode-view",
        }, "阅读"),
        h("button", {
          type: "button",
          className: mode === "edit" ? "active" : "",
          onClick: () => setMode("edit"),
          "data-testid": "doc-mode-edit",
        }, "编辑"),
      ),
      h("div", { className: "inline-actions" },
        h(RawButton, { title: `Doc ${record.id}`, data: record, onOpen: onRaw, testId: "doc-sidebar-raw" }),
      ),
    ),
    mode === "view"
      ? h(React.Fragment, null,
          h(DocDetailHeader, { record, onBack: onSelect ? () => onSelect(null) : undefined }),
          h(DocViewer, { record }),
        )
      : h(React.Fragment, null,
          h(UniDeskErrorBanner, { error, title: "保存失败" }),
          saveMsg ? h("p", { className: "muted paragraph", "data-testid": "doc-save-msg" }, saveMsg) : null,
          h(DocEditor, { form, saving, onChange: changeField, onSubmit: handleSubmit }),
        ),
  );
}

function DocWorkspace({ records, selectedRecord, onSelect, onSave, saving, saveError, saveMsg, onRaw }: AnyRecord) {
  const [leftOpen, setLeftOpen] = useState(true);
  const [rightOpen, setRightOpen] = useState(true);
  const [grouping, setGrouping] = useState("type");

  return h("div", { className: "doc-workspace", "data-testid": "doc-workspace" },
    h("div", { className: `doc-workspace-left ${leftOpen ? "open" : "collapsed"}` },
      h("div", { className: "doc-workspace-left-head" },
        h("span", { className: "panel-eyebrow" }, "目录树"),
        h("div", { className: "inline-actions" },
          h("button", {
            type: "button",
            className: `ghost-btn compact ${grouping === "type" ? "active" : ""}`,
            onClick: () => setGrouping("type"),
            "data-testid": "group-by-type",
          }, "按文类"),
          h("button", {
            type: "button",
            className: `ghost-btn compact ${grouping === "tag" ? "active" : ""}`,
            onClick: () => setGrouping("tag"),
            "data-testid": "group-by-tag",
          }, "按标签"),
          h("button", {
            type: "button",
            className: "ghost-btn compact",
            onClick: () => setLeftOpen((v: any) => !v),
            "data-testid": "toggle-left-panel",
          }, leftOpen ? "←" : "→"),
        ),
      ),
      leftOpen ? h(DocTypeTree, { records, onSelect, selectedId: selectedRecord?.id, activeGrouping: grouping }) : null,
    ),
    h("div", { className: "doc-workspace-center" },
      h("div", { className: "doc-record-list", "data-testid": "doc-record-list" },
        records.length === 0
          ? h(EmptyState, { title: "暂无记录", text: "通过 CLI 上传文书后会显示在这里。" })
          : records.map((record: any) => {
            const metadata = extractDocMetadata(record);
            return h("button", {
              key: record.id,
              type: "button",
              className: `doc-list-item ${selectedRecord?.id === record.id ? "selected" : ""}`,
              onClick: () => onSelect(record),
              "data-testid": `doc-record-item-${stableTestId(record.id)}`,
            },
              h("span", { className: "doc-list-meta" },
                h("span", null, metadata.docType || record.type || "--"),
                h(StatusBadge, { status: levelTone(metadata.priority || record.level) }, metadata.priority || record.level || "none"),
              ),
              h("span", { className: "doc-list-title" }, shortText(metadata.docNo ? `${metadata.docNo} ${record.title || ""}` : record.title || "--", 60)),
              h("span", { className: "doc-list-summary" }, shortText(record.summary || record.body, 100)),
            );
          }),
      ),
    ),
    h("div", { className: `doc-workspace-right ${rightOpen ? "open" : "collapsed"}` },
      h("div", { className: "doc-workspace-right-head" },
        h("button", {
          type: "button",
          className: "ghost-btn compact",
          onClick: () => setRightOpen((v: any) => !v),
          "data-testid": "toggle-right-panel",
        }, rightOpen ? "→" : "←"),
      ),
      rightOpen ? h(DocDetailSidebar, {
        record: selectedRecord,
        onSelect,
        onSave,
        saving,
        error: saveError,
        saveMsg,
        onRaw,
      }) : null,
    ),
  );
}

function recordFormFromCategory(categoryId: string): AnyRecord {
  const category = recordCategories.find((item) => item.id === categoryId) || recordCategories[0];
  return {
    id: "",
    category: category?.id || "external-goal",
    type: category?.type || "goal",
    level: category?.level || "G0",
    status: category?.status || "active",
    title: "",
    body: "",
    linkedGoalId: "",
    source: "",
    issueId: "",
    parentGoalId: "",
    childGoalIds: "",
    tags: tagsText(category?.tags || []),
    evidenceLinks: "",
    sourceSession: "frontend",
    taskId: "",
    commitId: "",
  };
}

function recordFormFromRecord(record: any): AnyRecord {
  return {
    id: record?.id || "",
    category: "custom",
    type: record?.type || "meeting",
    level: record?.level || "none",
    status: record?.status || "active",
    title: record?.title || "",
    body: record?.body || record?.summary || "",
    linkedGoalId: record?.linkedGoalId || "",
    source: recordStringField(record, ["source", "sourceLabel", "sourceFile"]) || firstRecordTagValue(record, "source"),
    issueId: recordStringField(record, ["issueId", "issue", "githubIssue", "githubIssueId", "externalIssue"]) || firstRecordTagValue(record, "issue"),
    parentGoalId: recordStringField(record, ["parentGoalId", "parentId", "parent"]) || firstRecordTagValue(record, "parent"),
    childGoalIds: tagsText([...recordStringArray(record, ["childGoalIds", "children", "childIds"]), ...recordTagValues(record, "child")]),
    tags: tagsText(record?.tags),
    evidenceLinks: tagsText(record?.evidenceLinks),
    sourceSession: record?.sourceSession || "frontend",
    taskId: record?.taskId || "",
    commitId: record?.commitId || "",
  };
}

function recordPayloadFromForm(form: AnyRecord): AnyRecord {
  const tags = parseCsv(form.tags);
  const metadataTags = [
    form.source ? `source:${String(form.source).trim()}` : "",
    form.issueId ? `issue:${String(form.issueId).trim()}` : "",
    form.parentGoalId ? `parent:${String(form.parentGoalId).trim()}` : "",
    ...parseCsv(form.childGoalIds).map((id) => `child:${id}`),
  ].filter(Boolean);
  return {
    type: form.type,
    level: form.level,
    status: form.status,
    title: String(form.title || "").trim(),
    body: String(form.body || "").trim(),
    linkedGoalId: String(form.linkedGoalId || "").trim(),
    // TODO(decision-center API): replace metadata tags with first-class fields:
    // source, issueId/taskId, parentGoalId and childGoalIds when the backend schema exposes them.
    tags: [...new Set([...tags, ...metadataTags])],
    evidenceLinks: parseCsv(form.evidenceLinks),
    sourceSession: String(form.source || form.sourceSession || "frontend").trim(),
    taskId: String(form.taskId || "").trim(),
    commitId: String(form.commitId || "").trim(),
  };
}

function isExternalGoal(record: any): boolean {
  const tags = Array.isArray(record.tags) ? record.tags.map((tag: string) => tag.toLowerCase()) : [];
  return record.type === "goal" && record.status !== "blocked" && record.status !== "parked" && (record.level === "G0" || tags.includes("external-goal"));
}

function isInternalGoal(record: any): boolean {
  const tags = Array.isArray(record.tags) ? record.tags.map((tag: string) => tag.toLowerCase()) : [];
  return record.type === "goal" && record.status !== "blocked" && record.status !== "parked" && !isExternalGoal(record) && (["G1", "G2", "G3"].includes(record.level) || tags.includes("internal-goal"));
}

function goalParentId(record: any): string {
  return recordStringField(record, ["parentGoalId", "parentId", "parent"]) || firstRecordTagValue(record, "parent") || record?.linkedGoalId || "";
}

function goalChildIds(record: any): string[] {
  return [...new Set([...recordStringArray(record, ["childGoalIds", "children", "childIds"]), ...recordTagValues(record, "child")])];
}

function recordMatchesRequirementView(record: any, view: string): boolean {
  if (view === "external-goal") return isExternalGoal(record);
  if (view === "internal-goal") return isInternalGoal(record);
  if (view === "blocker") return record.type === "blocker" || record.status === "blocked";
  if (view === "parked") return record.status === "parked";
  if (view === "authority") return ["decision", "experiment", "debt"].includes(record.type);
  return true;
}

function diaryFormFromEntry(entry: any): AnyRecord {
  const date = entry?.date || browserDateOnly();
  return {
    date,
    title: entry?.title || `${date} 工作日记`,
    body: entry?.body || "",
    sourceFile: entry?.sourceFile || defaultDiarySourceFile,
    tags: tagsText(entry?.tags || ["frontend"]),
  };
}

function diaryImportMarkdown(form: AnyRecord): string {
  const date = String(form.date || browserDateOnly()).trim();
  const title = String(form.title || `${date} 工作日记`).trim();
  const body = String(form.body || "").trim();
  const firstLine = body.split("\n")[0]?.trim() || "";
  if (firstLine === `# ${date}` || firstLine.startsWith(`# ${date} `) || firstLine === `# ${title}`) return body;
  return `# ${date}\n\n${body || `## ${title}\n`}`.trim();
}

function diaryPayloadFromForm(form: AnyRecord): AnyRecord {
  const date = String(form.date || browserDateOnly()).trim();
  const body = String(form.body || "").trim() || `# ${date}\n\n`;
  return {
    title: String(form.title || `${date} 工作日记`).trim(),
    body,
    sourceFile: String(form.sourceFile || defaultDiarySourceFile).trim() || defaultDiarySourceFile,
    tags: parseCsv(form.tags),
  };
}

function unavailableMessage(error: unknown, fallback: string): string {
  if (isUniDeskRequestError(error)) {
    const status = error.meta.status ? `HTTP ${error.meta.status}` : error.meta.kind;
    return `${fallback}（${status}）：${error.message || "后端接口暂不可用"}`;
  }
  return errorMessage(error, fallback);
}

function RecordCard({ record, onRaw, compact, onEdit }: AnyRecord) {
  const tags = recordTags(record);
  const evidence = Array.isArray(record.evidenceLinks) ? record.evidenceLinks : [];
  const issueTask = recordIssueTaskLabel(record);
  const source = recordSource(record);
  const parentId = goalParentId(record);
  const childIds = goalChildIds(record);
  return h("article", { className: `decision-record-card ${compact ? "compact" : ""}`, "data-testid": `decision-record-${stableTestId(record.id)}` },
    h("div", { className: "decision-record-head" },
      h("div", null,
        h("div", { className: "decision-record-meta" },
          h("span", null, record.type || "--"),
          h(StatusBadge, { status: levelTone(record.level) }, record.level || "none"),
          h(StatusBadge, { status: statusTone(record.status) }, record.status || "--"),
        ),
        h("strong", null, record.title || "--"),
      ),
      h("div", { className: "inline-actions" },
        onEdit ? h("button", { type: "button", className: "ghost-btn", onClick: () => onEdit(record), "data-testid": `edit-record-${stableTestId(record.id)}` }, "编辑") : null,
        h(RawButton, { title: `Decision ${record.id}`, data: record, onOpen: onRaw, testId: `raw-record-${stableTestId(record.id)}` }),
      ),
    ),
    h("div", { className: "decision-record-links", "data-testid": `decision-record-links-${stableTestId(record.id)}` },
      h("span", null, `source:${source}`),
      issueTask ? h("span", null, issueTask) : null,
      parentId ? h("span", null, `parent:${parentId}`) : null,
      childIds.length > 0 ? h("span", null, `children:${childIds.slice(0, 4).join(",")}`) : null,
    ),
    compact
      ? h("p", { className: "decision-summary" }, shortText(record.summary || record.body))
      : h(MarkdownBody, { markdown: record.body || record.summary || "", className: "decision-markdown" }),
    h("div", { className: "decision-record-foot" },
      record.linkedGoalId ? h("code", null, `goal:${record.linkedGoalId}`) : null,
      record.taskId ? h("code", null, `task:${record.taskId}`) : null,
      record.commitId ? h("code", null, record.commitId.slice(0, 12)) : null,
      h("span", null, fmtRecordTime(record.updatedAt)),
    ),
    tags.length > 0 ? h("div", { className: "decision-tags" }, tags.slice(0, 8).map((tag: string) => h("span", { key: tag }, tag))) : null,
    evidence.length > 0 ? h("div", { className: "decision-evidence" }, evidence.slice(0, 4).map((link: string) => h("a", { key: link, href: link, target: "_blank", rel: "noreferrer" }, shortText(link, 58)))) : null,
  );
}

function RecordTable({ records, onRaw, onEdit }: AnyRecord) {
  if (!records.length) return h(EmptyState, { title: "暂无记录", text: "通过 CLI 上传会议记录或决议后会显示在这里。", "data-testid": "decision-record-table-empty" });
  return h("div", { className: "table-wrap" },
    h("table", { className: "decision-table", "data-testid": "decision-center-record-table" },
      h("thead", null, h("tr", null,
        h("th", null, "等级"),
        h("th", null, "状态"),
        h("th", null, "类型"),
        h("th", null, "标题"),
        h("th", null, "摘要"),
        h("th", null, "证据"),
        h("th", null, "更新"),
        h("th", null, "操作"),
      )),
      h("tbody", null, records.map((record: any) => h("tr", { key: record.id },
        h("td", null, h(StatusBadge, { status: levelTone(record.level) }, record.level || "none")),
        h("td", null, h(StatusBadge, { status: statusTone(record.status) }, record.status || "--")),
        h("td", null, record.type || "--"),
        h("td", null, h("strong", null, record.title || "--"), record.linkedGoalId ? h("code", null, record.linkedGoalId) : null, h("span", { className: "muted block" }, recordIssueTaskLabel(record) || recordSource(record))),
        h("td", null, shortText(record.summary || record.body, 180)),
        h("td", null, Array.isArray(record.evidenceLinks) ? record.evidenceLinks.length : 0),
        h("td", null, fmtRecordTime(record.updatedAt)),
        h("td", null, h("div", { className: "inline-actions" },
          onEdit ? h("button", { type: "button", className: "ghost-btn", onClick: () => onEdit(record), "data-testid": `table-edit-record-${stableTestId(record.id)}` }, "编辑") : null,
          h(RawButton, { title: `Decision ${record.id}`, data: record, onOpen: onRaw, testId: `table-raw-record-${stableTestId(record.id)}` }),
        )),
      ))),
    ),
  );
}

function selectOptions(values: string[]): any[] {
  return values.map((value) => h("option", { key: value, value }, value));
}

function filteredQuery(filters: AnyRecord): string {
  const params = new URLSearchParams();
  if (filters.type !== "all") params.set("type", filters.type);
  if (filters.status !== "all") params.set("status", filters.status);
  if (filters.level !== "all") params.set("level", filters.level);
  if (filters.linkedGoalId.trim()) params.set("linkedGoalId", filters.linkedGoalId.trim());
  params.set("limit", "240");
  return params.toString();
}

function diaryQuery(filters: AnyRecord): string {
  const params = new URLSearchParams();
  if (filters.month !== "all") params.set("month", filters.month);
  if (filters.from.trim()) params.set("from", filters.from.trim());
  if (filters.to.trim()) params.set("to", filters.to.trim());
  params.set("limit", "180");
  return params.toString();
}

function diaryEntryLookupPath(entry: any): string {
  const key = entry?.id || entry?.date;
  const params = new URLSearchParams();
  if (entry?.sourceFile) params.set("sourceFile", String(entry.sourceFile));
  const query = params.toString();
  return `/api/diary/entries/${encodeURIComponent(key)}${query ? `?${query}` : ""}`;
}

function DiaryEntryCard({ entry, selected, onSelect, onRaw }: AnyRecord) {
  return h("article", { className: `diary-entry-card ${selected ? "selected" : ""}`, "data-testid": `diary-entry-${stableTestId(entry.date || entry.id)}` },
    h("button", { type: "button", className: "diary-entry-main", onClick: () => onSelect(entry) },
      h("span", { className: "diary-date" }, entry.date || "--"),
      h("strong", null, entry.title || entry.markdownPath || "--"),
      h("span", null, shortText(entry.summary || entry.body, 180)),
    ),
    h("div", { className: "decision-record-foot" },
      h("code", null, entry.markdownPath || "--"),
      h("span", null, fmtRecordTime(entry.updatedAt || entry.importedAt)),
      h(RawButton, { title: `Diary ${entry.date || entry.id}`, data: entry, onOpen: onRaw, testId: `raw-diary-entry-${stableTestId(entry.date || entry.id)}` }),
    ),
  );
}

function GoalBreakdown({ records, onEdit, onRaw }: AnyRecord) {
  const goals = records.filter((record: any) => record.type === "goal");
  const internalGoals = goals.filter(isInternalGoal);
  const childrenByParent = new Map<string, any[]>();
  for (const goal of internalGoals) {
    const parentId = goalParentId(goal);
    if (!parentId) continue;
    const bucket = childrenByParent.get(parentId) || [];
    bucket.push(goal);
    childrenByParent.set(parentId, bucket);
  }
  const externalGoals = goals.filter(isExternalGoal);
  if (externalGoals.length === 0) return h(EmptyState, { title: "暂无拆解关系", text: "创建 G0 外部目标后，可用 Linked Goal 或 parent 标签把内部目标关联上去。", "data-testid": "goal-breakdown-empty" });
  return h("div", { className: "goal-breakdown", "data-testid": "goal-breakdown" },
    externalGoals.slice(0, 12).map((goal: any) => {
      const explicitChildIds = goalChildIds(goal);
      const linkedChildren = [
        ...(childrenByParent.get(goal.id) || []),
        ...internalGoals.filter((child: any) => explicitChildIds.includes(child.id)),
      ].filter((child: any, index: number, array: any[]) => array.findIndex((item: any) => item.id === child.id) === index);
      const blockers = records.filter((record: any) => (record.type === "blocker" || record.status === "blocked") && (record.linkedGoalId === goal.id || goalChildIds(record).includes(goal.id)));
      return h("article", { key: goal.id, className: "goal-breakdown-item", "data-testid": `goal-breakdown-${stableTestId(goal.id)}` },
        h("div", { className: "goal-breakdown-head" },
          h("div", null,
            h("div", { className: "decision-record-meta" },
              h("span", null, "external"),
              h(StatusBadge, { status: levelTone(goal.level) }, goal.level || "G0"),
              h(StatusBadge, { status: statusTone(goal.status) }, goal.status || "--"),
            ),
            h("strong", null, goal.title || goal.id),
            h("span", { className: "muted block" }, recordIssueTaskLabel(goal) || recordSource(goal)),
          ),
          h("div", { className: "inline-actions" },
            h("button", { type: "button", className: "ghost-btn", onClick: () => onEdit(goal), "data-testid": `goal-breakdown-edit-${stableTestId(goal.id)}` }, "编辑"),
            h(RawButton, { title: `Goal ${goal.id}`, data: goal, onOpen: onRaw, testId: `goal-breakdown-raw-${stableTestId(goal.id)}` }),
          ),
        ),
        h("div", { className: "goal-breakdown-body" },
          h("div", { className: "goal-child-list" },
            h("span", { className: "panel-eyebrow" }, `内部目标 ${linkedChildren.length}`),
            linkedChildren.length === 0
              ? h("span", { className: "muted" }, "尚未拆解")
              : linkedChildren.slice(0, 6).map((child: any) => h("button", { key: child.id, type: "button", onClick: () => onEdit(child), "data-testid": `goal-child-${stableTestId(child.id)}` },
                h(StatusBadge, { status: levelTone(child.level) }, child.level),
                h("span", null, child.title || child.id),
              )),
          ),
          h("div", { className: "goal-child-list" },
            h("span", { className: "panel-eyebrow" }, `阻塞 ${blockers.length}`),
            blockers.length === 0
              ? h("span", { className: "muted" }, "无阻塞")
              : blockers.slice(0, 4).map((blocker: any) => h("button", { key: blocker.id, type: "button", onClick: () => onEdit(blocker), "data-testid": `goal-blocker-${stableTestId(blocker.id)}` },
                h(StatusBadge, { status: statusTone(blocker.status) }, blocker.status),
                h("span", null, blocker.title || blocker.id),
              )),
          ),
        ),
      );
    }),
  );
}

function DiaryCalendar({ month, entries, selectedDate, today, onPickDate, onOpenToday }: AnyRecord) {
  const entriesByDate = new Map(entries.map((entry: any) => [entry.date, entry]));
  return h("div", { className: "diary-calendar", "data-testid": "diary-calendar" },
    h("div", { className: "diary-calendar-head" },
      h("strong", null, month || "--"),
      h("button", { type: "button", className: "ghost-btn compact", onClick: onOpenToday, "data-testid": "diary-calendar-today" }, "今天"),
    ),
    h("div", { className: "diary-calendar-week" }, diaryWeekdays.map((day) => h("span", { key: day }, day))),
    h("div", { className: "diary-calendar-grid" },
      monthDateGrid(month).map((date, index) => {
        if (!date) return h("span", { key: `empty-${index}`, className: "diary-day empty" });
        const entry: any = entriesByDate.get(date);
        const classes = [
          "diary-day",
          entry ? "has-entry" : "",
          selectedDate === date ? "selected" : "",
          today === date ? "today" : "",
        ].filter(Boolean).join(" ");
        return h("button", {
          key: date,
          type: "button",
          className: classes,
          onClick: () => onPickDate(date, entry),
          "data-testid": `diary-calendar-day-${date}`,
        },
          h("span", null, date.slice(8)),
          entry ? h("i", null, shortText(entry.title || entry.summary, 24)) : null,
        );
      }),
    ),
  );
}

function RequirementBoard({ records, activeView, onView, onEdit, onRaw }: AnyRecord) {
  const groups = [
    { id: "external-goal", title: "外部目标", eyebrow: "G0 / user-facing", records: records.filter(isExternalGoal) },
    { id: "internal-goal", title: "内部目标", eyebrow: "G1-G3 / delivery", records: records.filter(isInternalGoal) },
    { id: "blocker", title: "阻塞", eyebrow: "P0-P1 / blocked", records: records.filter((record: any) => record.type === "blocker" || record.status === "blocked") },
    { id: "parked", title: "停放事项", eyebrow: "Parked", records: records.filter((record: any) => record.status === "parked") },
    { id: "authority", title: "决议/实验/债务", eyebrow: "Decision / Experiment / Debt", records: records.filter((record: any) => ["decision", "experiment", "debt"].includes(record.type)) },
  ];
  return h("div", { className: "requirement-workspace", "data-testid": "requirement-workspace" },
    h("div", { className: "requirement-switcher", role: "tablist", "aria-label": "需求视图" },
      requirementViews.map((item) => h("button", {
        key: item.id,
        type: "button",
        className: activeView === item.id ? "active" : "",
        onClick: () => onView(item.id),
        "data-testid": `requirement-filter-${item.id}`,
      }, item.label)),
    ),
    h("div", { className: "requirement-lanes" },
      groups.map((group) => {
        const visibleRecords = group.records.filter((record: any) => recordMatchesRequirementView(record, activeView)).slice(0, 10);
        return h("section", { key: group.id, className: "requirement-lane", "data-testid": `requirement-lane-${group.id}` },
          h("div", { className: "requirement-lane-head" },
            h("div", null,
              h("p", { className: "panel-eyebrow" }, group.eyebrow),
              h("strong", null, group.title),
            ),
            h(StatusBadge, { status: group.records.length > 0 ? "unknown" : "warn" }, group.records.length),
          ),
          visibleRecords.length === 0
            ? h(EmptyState, { title: "暂无条目", text: "用右侧录入台补齐该类需求或筛选条件。" })
            : h("div", { className: "decision-card-list" }, visibleRecords.map((record: any) => h(RecordCard, { key: record.id, record, onRaw, onEdit, compact: true }))),
        );
      }),
    ),
  );
}

function RecordEditor({ form, saving, message, error, onChange, onCategory, onSubmit, onReset }: AnyRecord) {
  return h("form", { className: "record-editor-form", onSubmit, "data-testid": "record-editor" },
    h("div", { className: "editor-mode-grid" },
      recordCategories.map((item) => h("button", {
        key: item.id,
        type: "button",
        className: form.category === item.id ? "active" : "",
        onClick: () => onCategory(item.id),
        "data-testid": `record-template-${item.id}`,
      }, item.label)),
    ),
    h("div", { className: "decision-form-grid" },
      h("label", null, "标题", h("input", { value: form.title, onChange: (event: any) => onChange("title", event.target.value), placeholder: "需求、阻塞、决议或实验标题", "data-testid": "record-title-input" })),
      h("label", null, "类型", h("select", { value: form.type, onChange: (event: any) => onChange("type", event.target.value), "data-testid": "record-type-select" }, selectOptions(recordTypes.filter((item) => item !== "all")))),
      h("label", null, "等级", h("select", { value: form.level, onChange: (event: any) => onChange("level", event.target.value), "data-testid": "record-level-select" }, selectOptions(recordLevels.filter((item) => item !== "all")))),
      h("label", null, "状态", h("select", { value: form.status, onChange: (event: any) => onChange("status", event.target.value), "data-testid": "record-status-select" }, selectOptions(recordStatuses.filter((item) => item !== "all")))),
      h("label", null, "Linked Goal", h("input", { value: form.linkedGoalId, onChange: (event: any) => onChange("linkedGoalId", event.target.value), placeholder: "关联目标 id" })),
      h("label", null, "Tags", h("input", { value: form.tags, onChange: (event: any) => onChange("tags", event.target.value), placeholder: "external-goal, requirement" })),
      h("label", null, "来源", h("input", { value: form.source, onChange: (event: any) => onChange("source", event.target.value), placeholder: "issue / customer / commander", "data-testid": "record-source-input" })),
      h("label", null, "Issue", h("input", { value: form.issueId, onChange: (event: any) => onChange("issueId", event.target.value), placeholder: "#22 或 URL", "data-testid": "record-issue-input" })),
      h("label", null, "父目标", h("input", { value: form.parentGoalId, onChange: (event: any) => onChange("parentGoalId", event.target.value), placeholder: "外部目标 id", "data-testid": "record-parent-goal-input" })),
      h("label", null, "子目标", h("input", { value: form.childGoalIds, onChange: (event: any) => onChange("childGoalIds", event.target.value), placeholder: "逗号分隔 id", "data-testid": "record-child-goals-input" })),
      h("label", { className: "wide" }, "正文 Markdown", h("textarea", { value: form.body, onChange: (event: any) => onChange("body", event.target.value), placeholder: "- 背景\n- 验收标准\n- 下一步", "data-testid": "record-body-editor" })),
      h("label", null, "证据链接", h("input", { value: form.evidenceLinks, onChange: (event: any) => onChange("evidenceLinks", event.target.value), placeholder: "逗号分隔 URL" })),
      h("label", null, "Task ID", h("input", { value: form.taskId, onChange: (event: any) => onChange("taskId", event.target.value), placeholder: "可选" })),
      h("label", null, "Commit ID", h("input", { value: form.commitId, onChange: (event: any) => onChange("commitId", event.target.value), placeholder: "可选" })),
    ),
    h("div", { className: "dispatch-actions" },
      h("button", { type: "submit", disabled: saving || !String(form.title || "").trim(), "data-testid": "save-record-button" }, saving ? "保存中" : form.id ? "保存记录" : "创建记录"),
      h("button", { type: "button", className: "ghost-btn", disabled: saving, onClick: onReset, "data-testid": "new-record-button" }, "新建"),
      form.id ? h("code", null, form.id) : null,
    ),
    message ? h("p", { className: "muted paragraph", "data-testid": "record-editor-message" }, message) : null,
    h(UniDeskErrorBanner, { error, title: "记录保存失败", wide: true }),
  );
}

function DiaryEditor({ form, saving, message, error, onChange, onToday, onSubmit }: AnyRecord) {
  return h("form", { className: "diary-editor-form", onSubmit, "data-testid": "diary-editor" },
    h("div", { className: "decision-form-grid diary-editor-grid" },
      h("label", null, "日期", h("input", { type: "date", value: form.date, onChange: (event: any) => onChange("date", event.target.value), "data-testid": "diary-date-input" })),
      h("label", null, "标题", h("input", { value: form.title, onChange: (event: any) => onChange("title", event.target.value), placeholder: "工作日记标题", "data-testid": "diary-title-input" })),
      h("label", null, "Source File", h("input", { value: form.sourceFile, onChange: (event: any) => onChange("sourceFile", event.target.value), placeholder: defaultDiarySourceFile, "data-testid": "diary-source-input" })),
      h("label", null, "Tags", h("input", { value: form.tags, onChange: (event: any) => onChange("tags", event.target.value), placeholder: "frontend, daily", "data-testid": "diary-tags-input" })),
      h("label", { className: "wide" }, "Markdown", h("textarea", { value: form.body, onChange: (event: any) => onChange("body", event.target.value), placeholder: "## 今日进展\n\n## 阻塞\n\n## 下一步", "data-testid": "diary-body-editor" })),
    ),
    h("div", { className: "dispatch-actions" },
      h("button", { type: "button", className: "ghost-btn", onClick: onToday, disabled: saving, "data-testid": "today-diary-button" }, "今天"),
      h("button", { type: "submit", disabled: saving || !String(form.date || "").trim(), "data-testid": "save-diary-button" }, saving ? "保存中" : "保存日记"),
      h("code", null, `${String(form.date || browserDateOnly()).slice(0, 7)}/${form.date || browserDateOnly()}.md`),
    ),
    message ? h("p", { className: "muted paragraph", "data-testid": "diary-editor-message" }, message) : null,
    h(UniDeskErrorBanner, { error, title: "日记保存失败", wide: true }),
  );
}

export function DecisionCenterPage({ microservices, onRaw, apiBaseUrl = "/api" }: AnyRecord) {
  const service = microservices.find((item: any) => item.id === "decision-center") || null;
  const [state, setState] = useState({ loading: false, error: "", health: null, records: [], refreshedAt: null, selectedDoc: null });
  const [filters, setFilters] = useState({ type: "all", status: "all", level: "all", linkedGoalId: "" });
  const [activeView, setActiveView] = useState("records");
  const [requirementView, setRequirementView] = useState("all");
  const [recordForm, setRecordForm] = useState(recordFormFromCategory("external-goal"));
  const [recordSaveState, setRecordSaveState] = useState({ saving: false, error: "", message: "" });
  const [diaryState, setDiaryState] = useState({ loading: false, error: "", entries: [], months: [], selected: null, refreshedAt: null });
  const todayDate = browserDateOnly();
  const [diaryFilters, setDiaryFilters] = useState({ month: monthFromDate(todayDate), from: "", to: "" });
  const [diaryForm, setDiaryForm] = useState(diaryFormFromEntry({ date: todayDate, title: `${todayDate} 工作日记`, tags: ["frontend"] }));
  const [diarySaveState, setDiarySaveState] = useState({ saving: false, error: "", message: "" });

  async function load(): Promise<void> {
    if (!service) return;
    setState((prev: any) => ({ ...prev, loading: true, error: "" }));
    try {
      const query = filteredQuery(filters);
      const records = await requestJson(decisionApi(apiBaseUrl, `/api/records?${query}`));
      const months = await requestJson(decisionApi(apiBaseUrl, "/api/diary/months"));
      let health: any = state.health;
      let healthError = "";
      try {
        health = await requestJson(`${apiBaseUrl}/microservices/decision-center/health`);
      } catch (err) {
        healthError = errorMessage(err, "Decision Center health 检查失败");
      }
      setState({ loading: false, error: healthError, health, records: Array.isArray(records.records) ? records.records : [], refreshedAt: new Date() });
      setDiaryState((prev: any) => ({ ...prev, months: Array.isArray(months.months) ? months.months : [] }));
    } catch (err) {
      setState((prev: any) => ({ ...prev, loading: false, error: unavailableMessage(err, "Decision Center API 暂不可用") }));
    }
  }

  async function loadDiary(): Promise<void> {
    if (!service) return;
    setDiaryState((prev: any) => ({ ...prev, loading: true, error: "" }));
    try {
      const entriesResponse = await requestJson(decisionApi(apiBaseUrl, `/api/diary/entries?${diaryQuery(diaryFilters)}`));
      const monthsResponse = await requestJson(decisionApi(apiBaseUrl, "/api/diary/months"));
      const entries = Array.isArray(entriesResponse.entries) ? entriesResponse.entries : [];
      const nextSelected = prevSelectedDiary(entries, diaryState.selected);
      setDiaryState((prev: any) => ({
        loading: false,
        error: "",
        entries,
        months: Array.isArray(monthsResponse.months) ? monthsResponse.months : prev.months,
        selected: nextSelected,
        refreshedAt: new Date(),
      }));
      if (nextSelected && !nextSelected.body) void selectDiaryEntry(nextSelected);
    } catch (err) {
      setDiaryState((prev: any) => ({ ...prev, loading: false, error: unavailableMessage(err, "日记 API 暂不可用") }));
    }
  }

  async function selectDiaryEntry(entry: any): Promise<void> {
    setDiaryState((prev: any) => ({ ...prev, selected: entry }));
    try {
      const response = await requestJson(decisionApi(apiBaseUrl, diaryEntryLookupPath(entry)));
      const selected = response.entry || entry;
      setDiaryState((prev: any) => ({ ...prev, selected }));
      setDiaryForm(diaryFormFromEntry(selected));
    } catch (err) {
      setDiaryState((prev: any) => ({ ...prev, error: errorMessage(err, "日记正文加载失败") }));
    }
  }

  function resetRecordForm(category = "external-goal"): void {
    setRecordForm(recordFormFromCategory(category));
    setRecordSaveState({ saving: false, error: "", message: "" });
  }

  function changeRecordForm(field: string, value: any): void {
    setRecordForm((prev: any) => ({ ...prev, [field]: value, category: field === "type" || field === "level" || field === "status" ? "custom" : prev.category }));
  }

  function selectRecordCategory(category: string): void {
    const next = recordFormFromCategory(category);
    setRecordForm((prev: any) => ({
      ...prev,
      ...next,
      id: prev.id || "",
      title: prev.title || "",
      body: prev.body || "",
      linkedGoalId: prev.linkedGoalId || "",
      source: prev.source || "",
      issueId: prev.issueId || "",
      parentGoalId: prev.parentGoalId || "",
      childGoalIds: prev.childGoalIds || "",
      evidenceLinks: prev.evidenceLinks || "",
      sourceSession: prev.sourceSession || "frontend",
      taskId: prev.taskId || "",
      commitId: prev.commitId || "",
    }));
  }

  async function editRecord(record: any): Promise<void> {
    setRecordForm(recordFormFromRecord(record));
    setRecordSaveState({ saving: false, error: "", message: `正在编辑 ${record?.id || ""}` });
    setActiveView("records");
    if (!record?.id || record?.body) return;
    try {
      const response = await requestJson(decisionApi(apiBaseUrl, `/api/records/${encodeURIComponent(record.id)}`));
      const fullRecord = response.record || record;
      setRecordForm(recordFormFromRecord(fullRecord));
    } catch (err) {
      setRecordSaveState({ saving: false, error: errorMessage(err, "记录正文加载失败"), message: "" });
    }
  }

  async function saveRecord(event: any): Promise<void> {
    event.preventDefault();
    const payload = recordPayloadFromForm(recordForm);
    if (!payload.title) {
      setRecordSaveState({ saving: false, error: "标题不能为空", message: "" });
      return;
    }
    setRecordSaveState({ saving: true, error: "", message: "" });
    try {
      const editingId = String(recordForm.id || "").trim();
      const response = await requestJson(
        decisionApi(apiBaseUrl, editingId ? `/api/records/${encodeURIComponent(editingId)}` : "/api/records"),
        { method: editingId ? "PUT" : "POST", body: payload },
      );
      const saved = response.record;
      setRecordForm(recordFormFromRecord(saved || { ...payload, id: editingId }));
      setRecordSaveState({ saving: false, error: "", message: `${editingId ? "已保存" : "已创建"} ${saved?.id || editingId || ""}` });
      await load();
    } catch (err) {
      setRecordSaveState({ saving: false, error: errorMessage(err, "记录保存失败"), message: "" });
    }
  }

  function changeDiaryForm(field: string, value: any): void {
    setDiaryForm((prev: any) => ({ ...prev, [field]: value }));
    if (field === "date" && /^\d{4}-\d{2}-\d{2}$/u.test(String(value || ""))) {
      setDiaryFilters((prev: any) => ({ ...prev, month: monthFromDate(String(value)) }));
    }
  }

  async function openTodayDiary(): Promise<void> {
    const today = browserDateOnly();
    setActiveView("diary");
    setDiaryFilters((prev: any) => ({ ...prev, month: monthFromDate(today) }));
    setDiarySaveState({ saving: false, error: "", message: "" });
    try {
      const response = await requestJson(decisionApi(apiBaseUrl, `/api/diary/entries/${encodeURIComponent(today)}`));
      const entry = response.entry;
      setDiaryState((prev: any) => ({ ...prev, selected: entry || prev.selected }));
      setDiaryForm(diaryFormFromEntry(entry || { date: today, title: `${today} 工作日记`, tags: ["frontend"] }));
      setDiarySaveState({ saving: false, error: "", message: entry ? `已打开今天 ${today}` : `已准备今天 ${today}` });
    } catch {
      setDiaryForm(diaryFormFromEntry({ date: today, title: `${today} 工作日记`, body: `## 今日进展\n\n## 阻塞\n\n## 下一步\n`, sourceFile: defaultDiarySourceFile, tags: ["frontend"] }));
      setDiarySaveState({ saving: false, error: "", message: `今天 ${today} 尚未存在，保存后自动创建` });
    }
  }

  async function pickDiaryDate(date: string, entry?: any): Promise<void> {
    setActiveView("diary");
    setDiaryFilters((prev: any) => ({ ...prev, month: monthFromDate(date) }));
    setDiarySaveState({ saving: false, error: "", message: "" });
    if (entry) {
      await selectDiaryEntry(entry);
      return;
    }
    const next = diaryFormFromEntry({ date, title: `${date} 工作日记`, body: `## 今日进展\n\n## 阻塞\n\n## 下一步\n`, sourceFile: defaultDiarySourceFile, tags: ["frontend"] });
    setDiaryState((prev: any) => ({ ...prev, selected: null }));
    setDiaryForm(next);
    setDiarySaveState({ saving: false, error: "", message: `${date} 尚未存在，保存后自动创建` });
  }

  async function saveDiary(event: any): Promise<void> {
    event.preventDefault();
    const date = String(diaryForm.date || "").trim();
    if (!date) {
      setDiarySaveState({ saving: false, error: "日期不能为空", message: "" });
      return;
    }
    setDiarySaveState({ saving: true, error: "", message: "" });
    try {
      const response = await requestJson(decisionApi(apiBaseUrl, `/api/diary/entries/${encodeURIComponent(date)}`), {
        method: "PUT",
        body: diaryPayloadFromForm(diaryForm),
      });
      const entry = response.entry;
      setDiarySaveState({ saving: false, error: "", message: `已保存 ${date} / ${entry?.markdownPath || "YYYY-MM/YYYY-MM-DD.md"}` });
      await loadDiary();
      if (entry) await selectDiaryEntry(entry);
    } catch (err) {
      try {
        const markdown = diaryImportMarkdown(diaryForm);
        const response = await requestJson(decisionApi(apiBaseUrl, "/api/diary/import"), {
          method: "POST",
          body: {
            markdown,
            sourceFile: String(diaryForm.sourceFile || defaultDiarySourceFile).trim() || defaultDiarySourceFile,
            tags: parseCsv(diaryForm.tags),
          },
        });
        const entry = Array.isArray(response.entries) ? response.entries.find((item: any) => item.date === date) || response.entries[0] : null;
        setDiarySaveState({ saving: false, error: "", message: `已保存 ${date} / ${response.pathPattern || "YYYY-MM/YYYY-MM-DD.md"}` });
        await loadDiary();
        if (entry) await selectDiaryEntry(entry);
      } catch (fallbackError) {
        setDiarySaveState({ saving: false, error: unavailableMessage(fallbackError, "日记保存失败"), message: "" });
      }
    }
  }

  function prevSelectedDiary(entries: any[], selected: any): any {
    if (selected && entries.some((entry: any) => entry.id === selected.id)) return selected;
    return entries[0] || null;
  }

  useEffect(() => {
    load();
  }, [service?.id, service?.runtime?.providerStatus]);

  useEffect(() => {
    const timer = setTimeout(() => void load(), 120);
    return () => clearTimeout(timer);
  }, [filters.type, filters.status, filters.level, filters.linkedGoalId]);

  useEffect(() => {
    if (activeView !== "diary") return;
    const timer = setTimeout(() => void loadDiary(), 120);
    return () => clearTimeout(timer);
  }, [activeView, diaryFilters.month, diaryFilters.from, diaryFilters.to, service?.id, service?.runtime?.providerStatus]);

  if (!service) return h(EmptyState, { title: "Decision Center 未登记", text: "请在 config.json 的 microservices 中登记用户服务 id=decision-center" });

  const runtime = microserviceRuntime(service);
  const repository = microserviceRepository(service);
  const backend = microserviceBackend(service);
  const records = Array.isArray(state.records) ? state.records : [];
  const externalGoals = records.filter((record: any) => isExternalGoal(record) && record.status !== "done");
  const internalGoals = records.filter((record: any) => isInternalGoal(record) && record.status !== "done");
  const blockers = records.filter((record: any) => (record.type === "blocker" || record.status === "blocked") && record.status !== "done").slice(0, 8);
  const parked = records.filter((record: any) => record.status === "parked").slice(0, 8);
  const authorityRecords = records.filter((record: any) => ["decision", "experiment", "debt"].includes(record.type)).slice(0, 12);
  const recentMeetings = records.filter((record: any) => record.type === "meeting" || record.type === "decision").slice(0, 12);
  const requirementFilteredRecords = records.filter((record: any) => recordMatchesRequirementView(record, requirementView));
  const diaryEntries = Array.isArray(diaryState.entries) ? diaryState.entries : [];
  const diaryMonths = Array.isArray(diaryState.months) ? diaryState.months : [];
  const selectedDiary = diaryState.selected;
  const diaryCount = Number(state.health?.diaryEntryCount ?? 0);
  const currentDiaryMonth = diaryFilters.month === "all" ? monthFromDate(String(diaryForm.date || browserDateOnly())) : diaryFilters.month;

  return h("div", { className: "decision-center-page", "data-testid": "decision-center-page" },
    h(Panel, { title: "Decision Center", eyebrow: "Authority Records", loading: state.loading, actions: h("div", { className: "inline-actions" },
      h("button", { type: "button", className: "ghost-btn", onClick: () => void load(), disabled: state.loading, "data-testid": "decision-refresh-button" }, state.loading ? "刷新中" : "刷新"),
      h(RawButton, { title: "Decision Center Health", data: state.health, onOpen: onRaw, testId: "raw-decision-center-health" }),
    ) },
      h("div", { className: "decision-hero" },
        h("div", { className: "metric-grid" },
          h(MetricCard, { label: "记录数", value: records.length, hint: `PostgreSQL / ${state.health?.storage || "postgres"}`, tone: "ok" }),
          h(MetricCard, { label: "日记", value: diaryCount, hint: "按月 Markdown", tone: diaryCount > 0 ? "ok" : "warn" }),
          h(MetricCard, { label: "外部/内部目标", value: `${externalGoals.length}/${internalGoals.length}`, hint: "G0-facing / G1-G3 delivery", tone: "ok" }),
          h(MetricCard, { label: "P0/P1 Blocker", value: blockers.length, hint: "requires decision", tone: blockers.length > 0 ? "warn" : "ok" }),
        ),
        h("div", { className: "microservice-ref-card" },
          h("span", null, "Runtime"),
          h("strong", null, runtime.orchestrator || service.deployment?.mode || "k3sctl"),
          h("code", null, `${service.providerId} / ${backend.nodeBindHost || "--"}:${backend.nodePort || "--"}`),
          h("code", null, repository.commitId || "--"),
        ),
      ),
      h(UniDeskErrorBanner, { error: state.error, title: "Decision Center 请求失败" }),
    ),
    h("div", { className: "decision-tabs", role: "tablist" },
      h("button", { type: "button", className: activeView === "records" ? "active" : "", onClick: () => setActiveView("records"), "data-testid": "decision-tab-requirements" }, "需求管理"),
      h("button", { type: "button", className: activeView === "diary" ? "active" : "", onClick: () => setActiveView("diary"), "data-testid": "decision-tab-diary" }, "工作日记"),
      h("button", { type: "button", className: activeView === "workspace" ? "active" : "", onClick: () => setActiveView("workspace"), "data-testid": "decision-tab-workspace" }, "文书工作台"),
    ),
    activeView === "workspace" ? h(React.Fragment, null,
      h(DocWorkspace, {
        records,
        selectedRecord: state.selectedDoc,
        onSelect: async (record: any) => {
          setState((prev: any) => ({ ...prev, selectedDoc: record }));
          if (!record?.body && record?.id) {
            try {
              const response = await requestJson(decisionApi(apiBaseUrl, `/api/records/${encodeURIComponent(record.id)}`));
              setState((prev: any) => ({ ...prev, selectedDoc: response.record || record }));
            } catch { /* ignore */ }
          }
        },
        onSave: async (form: AnyRecord) => {
          setRecordSaveState({ saving: true, error: "", message: "" });
          try {
            const editingId = String(form.id || "").trim();
            const response = await requestJson(
              decisionApi(apiBaseUrl, editingId ? `/api/records/${encodeURIComponent(editingId)}` : "/api/records"),
              { method: editingId ? "PUT" : "POST", body: recordPayloadFromForm(form) },
            );
            const saved = response.record;
            setRecordSaveState({ saving: false, error: "", message: `已保存 ${saved?.id || editingId}` });
            await load();
            if (saved) setState((prev: any) => ({ ...prev, selectedDoc: saved }));
          } catch (err) {
            setRecordSaveState({ saving: false, error: errorMessage(err, "保存失败"), message: "" });
          }
        },
        saving: recordSaveState.saving,
        saveError: recordSaveState.error,
        saveMsg: recordSaveState.message,
        onRaw,
      }),
    ) : activeView === "diary" ? h(React.Fragment, null,
      h(Panel, { title: "工作日记编辑台", eyebrow: "Daily Markdown", loading: diarySaveState.saving, actions: h("div", { className: "inline-actions" },
        h("button", { type: "button", className: "ghost-btn", onClick: () => void openTodayDiary(), disabled: diarySaveState.saving, "data-testid": "today-diary" }, "今天"),
      ) },
        h(DiaryEditor, {
          form: diaryForm,
          saving: diarySaveState.saving,
          message: diarySaveState.message,
          error: diarySaveState.error,
          onChange: changeDiaryForm,
          onToday: () => void openTodayDiary(),
          onSubmit: (event: any) => void saveDiary(event),
        }),
      ),
      h(Panel, { title: "日记筛选", eyebrow: "Markdown by Month", loading: diaryState.loading, actions: h("div", { className: "inline-actions" },
        h("button", { type: "button", className: "ghost-btn", onClick: () => void loadDiary(), disabled: diaryState.loading, "data-testid": "diary-refresh-button" }, diaryState.loading ? "刷新中" : "刷新"),
        h(RawButton, { title: "Diary Months", data: diaryMonths, onOpen: onRaw, testId: "raw-decision-center-diary-months" }),
      ) },
        h("div", { className: "decision-filter-bar", "data-testid": "diary-filter-bar" },
          h("label", null, "月份", h("select", { value: diaryFilters.month, onChange: (event: any) => setDiaryFilters((prev: any) => ({ ...prev, month: event.target.value })), "data-testid": "diary-month-select" },
            h("option", { value: "all" }, "all"),
            diaryMonths.some((month: any) => month.month === currentDiaryMonth) ? null : h("option", { value: currentDiaryMonth }, `${currentDiaryMonth} (0)`),
            diaryMonths.map((month: any) => h("option", { key: month.month, value: month.month }, `${month.month} (${month.count})`)),
          )),
          h("label", null, "开始日期", h("input", { type: "date", value: diaryFilters.from, onChange: (event: any) => setDiaryFilters((prev: any) => ({ ...prev, from: event.target.value })), "data-testid": "diary-from-input" })),
          h("label", null, "结束日期", h("input", { type: "date", value: diaryFilters.to, onChange: (event: any) => setDiaryFilters((prev: any) => ({ ...prev, to: event.target.value })), "data-testid": "diary-to-input" })),
          h("label", null, "存储", h("input", { value: "PostgreSQL / YYYY-MM/YYYY-MM-DD.md", readOnly: true })),
        ),
        h(DiaryCalendar, {
          month: currentDiaryMonth,
          entries: diaryEntries,
          selectedDate: String(diaryForm.date || selectedDiary?.date || ""),
          today: browserDateOnly(),
          onPickDate: (date: string, entry: any) => void pickDiaryDate(date, entry),
          onOpenToday: () => void openTodayDiary(),
        }),
        h(UniDeskErrorBanner, { error: diaryState.error, title: "日记请求失败" }),
      ),
      h("div", { className: "diary-layout" },
        h(Panel, { title: "按天条目", eyebrow: `${diaryEntries.length} Entries`, loading: diaryState.loading },
          diaryEntries.length === 0
            ? h(EmptyState, { title: "暂无日记", text: "点击“今天”后可自动创建当天 Markdown 日记。", "data-testid": "diary-entry-list-empty" })
            : h("div", { className: "diary-entry-list" }, diaryEntries.map((entry: any) => h(DiaryEntryCard, { key: entry.id, entry, selected: selectedDiary?.id === entry.id, onSelect: selectDiaryEntry, onRaw }))),
        ),
        h(Panel, { title: selectedDiary?.title || "日记正文", eyebrow: selectedDiary?.markdownPath || "Daily Markdown", actions: selectedDiary ? h(RawButton, { title: `Diary ${selectedDiary.date}`, data: selectedDiary, onOpen: onRaw, testId: "raw-decision-center-diary-selected" }) : null },
          selectedDiary
            ? h(MarkdownBody, { markdown: selectedDiary.body || selectedDiary.summary || "", className: "decision-markdown diary-markdown" })
            : h(EmptyState, { title: "未选择日记", text: "从左侧选择一天查看 Markdown 正文。" }),
        ),
      ),
    ) : h(React.Fragment, null,
    h(Panel, { title: "需求管理工作区", eyebrow: `${requirementFilteredRecords.length} Filtered`, loading: state.loading },
      h(RequirementBoard, { records, activeView: requirementView, onView: setRequirementView, onEdit: editRecord, onRaw }),
    ),
    h(Panel, { title: "目标拆解", eyebrow: "External to Internal Goals" },
      h(GoalBreakdown, { records, onEdit: editRecord, onRaw }),
    ),
    h(Panel, { title: recordForm.id ? "编辑需求记录" : "录入需求记录", eyebrow: "Record Editor", loading: recordSaveState.saving },
      h(RecordEditor, {
        form: recordForm,
        saving: recordSaveState.saving,
        message: recordSaveState.message,
        error: recordSaveState.error,
        onChange: changeRecordForm,
        onCategory: selectRecordCategory,
        onSubmit: (event: any) => void saveRecord(event),
        onReset: () => resetRecordForm(),
      }),
    ),
    h(Panel, { title: "筛选", eyebrow: "Type / Status / Level" },
      h("div", { className: "decision-filter-bar", "data-testid": "decision-center-filters" },
        h("label", null, "类型", h("select", { value: filters.type, onChange: (event: any) => setFilters((prev: any) => ({ ...prev, type: event.target.value })) }, selectOptions(recordTypes))),
        h("label", null, "状态", h("select", { value: filters.status, onChange: (event: any) => setFilters((prev: any) => ({ ...prev, status: event.target.value })) }, selectOptions(recordStatuses))),
        h("label", null, "等级", h("select", { value: filters.level, onChange: (event: any) => setFilters((prev: any) => ({ ...prev, level: event.target.value })) }, selectOptions(recordLevels))),
        h("label", null, "Linked Goal", h("input", { value: filters.linkedGoalId, onChange: (event: any) => setFilters((prev: any) => ({ ...prev, linkedGoalId: event.target.value })), placeholder: "goal id" })),
      ),
    ),
    h("div", { className: "decision-default-grid" },
      h(Panel, { title: "外部目标", eyebrow: `${externalGoals.length} External Goals` },
        externalGoals.length === 0 ? h(EmptyState, { title: "暂无外部目标", text: "外部目标使用 G0 或 external-goal tag。" }) :
          h("div", { className: "decision-card-list" }, externalGoals.slice(0, 8).map((record: any) => h(RecordCard, { key: record.id, record, onRaw, onEdit: editRecord, compact: true }))),
      ),
      h(Panel, { title: "内部目标", eyebrow: `${internalGoals.length} Internal Goals` },
        internalGoals.length === 0 ? h(EmptyState, { title: "暂无内部目标", text: "内部目标使用 G1/G2/G3 或 internal-goal tag。" }) :
          h("div", { className: "decision-card-list" }, internalGoals.slice(0, 8).map((record: any) => h(RecordCard, { key: record.id, record, onRaw, onEdit: editRecord, compact: true }))),
      ),
      h(Panel, { title: "P0/P1 Blocker", eyebrow: `${blockers.length} Blockers` },
        blockers.length === 0 ? h(EmptyState, { title: "暂无高优先级阻塞", text: "阻塞记录使用 type=blocker 且 level=P0/P1。" }) :
          h("div", { className: "decision-card-list" }, blockers.map((record: any) => h(RecordCard, { key: record.id, record, onRaw, onEdit: editRecord, compact: true }))),
      ),
      h(Panel, { title: "停放事项", eyebrow: `${parked.length} Parked` },
        parked.length === 0 ? h(EmptyState, { title: "暂无停放事项", text: "status=parked 的记录会集中展示。" }) :
          h("div", { className: "decision-card-list" }, parked.map((record: any) => h(RecordCard, { key: record.id, record, onRaw, onEdit: editRecord, compact: true }))),
      ),
      h(Panel, { title: "决议/实验/债务", eyebrow: `${authorityRecords.length} Authority` },
        authorityRecords.length === 0 ? h(EmptyState, { title: "暂无权威事项", text: "决议、实验和债务会集中展示。" }) :
          h("div", { className: "decision-card-list" }, authorityRecords.map((record: any) => h(RecordCard, { key: record.id, record, onRaw, onEdit: editRecord, compact: true }))),
      ),
      h(Panel, { title: "最近会议/决议", eyebrow: `${recentMeetings.length} Recent` },
        recentMeetings.length === 0 ? h(EmptyState, { title: "暂无会议或决议", text: "使用 CLI 上传 Markdown 会议记录后会显示。" }) :
          h("div", { className: "decision-card-list" }, recentMeetings.map((record: any) => h(RecordCard, { key: record.id, record, onRaw, onEdit: editRecord, compact: true }))),
      ),
    ),
    h(Panel, { title: "全部记录", eyebrow: `${records.length} Records`, actions: state.refreshedAt ? h("span", { className: "muted" }, `刷新 ${fmtClock(state.refreshedAt)}`) : null },
      h(RecordTable, { records, onRaw, onEdit: editRecord }),
    ),
    ),
  );
}
