import type { WorkbenchModuleKey, WorkbenchModuleMeta } from './use-workbench-modules';
import type { WorkbenchGridItem, WorkbenchLayout } from './workbench-layout-types';

/**
 * 把存量布局与当前模块注册中心对齐。
 * - 布局含但注册中心已删除的 key：丢弃
 * - 注册中心存在但布局未含的 key：按 defaultVisible 落入网格底部或 hidden
 */
export function reconcileLayout(layout: WorkbenchLayout, modules: WorkbenchModuleMeta[]): WorkbenchLayout {
  const knownKeys = new Set<WorkbenchModuleKey>(modules.map(m => m.key));
  const metaByKey = new Map<WorkbenchModuleKey, WorkbenchModuleMeta>(modules.map(m => [m.key, m]));

  // 最小宽高是组件固有能力下限，始终以 meta 为准刷新（不被旧存储固化），并把 w/h clamp 到不低于下限
  const grid: WorkbenchGridItem[] = layout.grid
    .filter(item => knownKeys.has(item.i))
    .map(item => {
      const { minW, minH } = metaByKey.get(item.i)!.defaultGrid;
      return { ...item, minW, minH, w: Math.max(item.w, minW), h: Math.max(item.h, minH) };
    });
  const hidden = layout.hidden.filter(k => knownKeys.has(k));

  const appearKeys = new Set<WorkbenchModuleKey>([...grid.map(g => g.i), ...hidden]);

  let nextY = grid.reduce((max, g) => Math.max(max, g.y + g.h), 0);

  // 注册中心存在但布局未含的 key：可见的落网格底部，其余进 hidden
  for (const m of modules.filter(item => !appearKeys.has(item.key))) {
    if (m.defaultVisible) {
      grid.push({
        i: m.key,
        x: m.defaultGrid.x,
        y: nextY,
        w: m.defaultGrid.w,
        h: m.defaultGrid.h,
        minW: m.defaultGrid.minW,
        minH: m.defaultGrid.minH
      });
      nextY += m.defaultGrid.h;
    } else {
      hidden.push(m.key);
    }
  }

  return { ...layout, grid, hidden };
}
