export interface PageTreeNode {
  title: string;
  value: string;
  key: string;
  children?: PageTreeNode[];
}

interface RawPage {
  id: number | string;
  parentId?: number | string | null;
  sortOrder?: number | null;
  [key: string]: any;
}

/**
 * 将平铺的 page 列表构建成 TreeSelect 所需的树结构。
 *
 * @param pages     后端返回的平铺 page 数组
 * @param getTitle  从单条 page 记录提取显示文本的函数（支持多语言/自定义逻辑）
 */
export function buildPageTree(
  pages: RawPage[],
  getTitle: (page: RawPage) => string,
): PageTreeNode[] {
  const nodeMap = new Map<
    string,
    { node: PageTreeNode; parentId: string | null; sortOrder: number | null }
  >();

  pages.forEach((page) => {
    const id = String(page.id);
    const parentId = page.parentId != null ? String(page.parentId) : null;
    const sortOrder = page.sortOrder ?? null;
    nodeMap.set(id, {
      node: { title: getTitle(page), value: id, key: id, children: [] },
      parentId,
      sortOrder,
    });
  });

  const roots: PageTreeNode[] = [];
  nodeMap.forEach(({ node, parentId }) => {
    if (parentId !== null && nodeMap.has(parentId)) {
      nodeMap.get(parentId)!.node.children!.push(node);
    } else {
      roots.push(node);
    }
  });

  const sortOrderMap = new Map<string, number | null>();
  nodeMap.forEach(({ sortOrder }, id) => sortOrderMap.set(id, sortOrder));

  const sortNodes = (nodes: PageTreeNode[]) => {
    nodes.sort((a, b) => {
      const orderA = sortOrderMap.get(a.key) ?? Infinity;
      const orderB = sortOrderMap.get(b.key) ?? Infinity;
      return (orderA as number) - (orderB as number);
    });
    nodes.forEach((n) => {
      if (n.children?.length) sortNodes(n.children);
    });
  };

  const pruneEmptyChildren = (nodes: PageTreeNode[]): PageTreeNode[] =>
    nodes.map((n) => {
      if (n.children?.length)
        return { ...n, children: pruneEmptyChildren(n.children) };
      const { children, ...rest } = n;
      return rest as PageTreeNode;
    });

  sortNodes(roots);
  return pruneEmptyChildren(roots);
}
