/**
 * Logic Tree Layout - 逻辑树布局
 * 
 * 结构：
 *   根节点（左侧）
 *     ├── 子节点1 ──┬── 孙节点1.1
 *     │             └── 孙节点1.2
 *     ├── 子节点2
 *     └── 子节点3
 * 
 * 特点：
 * - 根节点在左侧
 * - 子节点向右展开
 * - 支持多层级展开
 * - 适合表达逻辑关系、流程分支
 * 
 * 命名说明：
 * - "逻辑树"是行业通用术语
 * - 类似于 MindManager 的 "Logic Map" 模式
 * - 不同于真正的思维导图（Radial Mindmap）
 */

import { LayoutEngine, layoutRegistry } from './LayoutEngine'
import type { Node, Point, IGraphModel } from '../core/types'

export class LogicTreeLayout extends LayoutEngine {
  readonly type = 'logic-tree' as const

  /** 默认配置 */
  protected config = {
    nodeSpacingX: 200,
    nodeSpacingY: 60,
    rootPosition: { x: 100, y: 300 },
    levelGap: 200,          // 层级间距
    siblingGap: 50,         // 兄弟节点间距
    subtreeGap: 30          // 子树间距
  }

  layout(graph: IGraphModel): Map<string, Point> {
    const positions = new Map<string, Point>()
    const root = graph.root

    if (!root) return positions

    // 根节点位置
    positions.set(root.id, { ...this.config.rootPosition })

    // 递归布局子节点
    this.layoutChildren(root, graph, positions, 0)

    return positions
  }

  private layoutChildren(
    parent: Node,
    graph: IGraphModel,
    positions: Map<string, Point>,
    level: number
  ): void {
    const children = graph.getChildren(parent.id).filter(n => !n.hidden)
    if (children.length === 0) return

    const parentPos = positions.get(parent.id)
    if (!parentPos) return

    // 计算所有子节点的总高度
    const totalHeight = children.reduce((sum, child) => {
      const subtreeSize = this.calcSubtreeSize(child, graph, 36, this.config.subtreeGap)
      return sum + subtreeSize
    }, 0)

    // 子节点的起始Y坐标
    let currentY = parentPos.y - totalHeight / 2

    // 子节点的X坐标
    const childX = parentPos.x + this.config.levelGap

    children.forEach(child => {
      const subtreeSize = this.calcSubtreeSize(child, graph, 36, this.config.subtreeGap)
      const childY = currentY + subtreeSize / 2

      positions.set(child.id, { x: childX, y: childY })

      // 递归布局孙节点
      this.layoutChildren(child, graph, positions, level + 1)

      currentY += subtreeSize
    })
  }
}

// 注册布局引擎
layoutRegistry.register(new LogicTreeLayout())

export default LogicTreeLayout
