import { getOverviewGridDims } from "./floorMapCanvasStage.js";
/**
* 行列数尽量接近正方形（复用全览网格算法）。
*/
function getSquareishGridDims(count) {
	return getOverviewGridDims(count);
}
/**
* 计算批量落点左上角坐标列表（行优先：先填满第一行再换行）。
*/
function computeBatchScenePlacementPositions(sizes, ctx) {
	var _ctx$boundingPadding;
	const count = sizes.length;
	if (count === 0) return [];
	const gap = 16;
	const pad = Math.max(0, (_ctx$boundingPadding = ctx.boundingPadding) !== null && _ctx$boundingPadding !== void 0 ? _ctx$boundingPadding : 24);
	const { cols, rows } = getSquareishGridDims(count);
	const colWidths = Array.from({ length: cols }, () => 0);
	const rowHeights = Array.from({ length: rows }, () => 0);
	for (let i = 0; i < count; i += 1) {
		const col = i % cols;
		const row = Math.floor(i / cols);
		colWidths[col] = Math.max(colWidths[col], sizes[i].width);
		rowHeights[row] = Math.max(rowHeights[row], sizes[i].height);
	}
	let anchorX = pad;
	let anchorY = pad;
	if (ctx.existingElements.length > 0) {
		const maxRight = Math.max(...ctx.existingElements.map((e) => e.x + e.width));
		const minTop = Math.min(...ctx.existingElements.map((e) => e.y));
		anchorX = maxRight + gap;
		anchorY = Math.max(pad, minTop);
	}
	const colOffsets = [];
	let xCursor = 0;
	for (let c = 0; c < cols; c += 1) {
		colOffsets[c] = xCursor;
		xCursor += colWidths[c] + (c < cols - 1 ? gap : 0);
	}
	const rowOffsets = [];
	let yCursor = 0;
	for (let r = 0; r < rows; r += 1) {
		rowOffsets[r] = yCursor;
		yCursor += rowHeights[r] + (r < rows - 1 ? gap : 0);
	}
	const positions = [];
	for (let i = 0; i < count; i += 1) {
		const col = i % cols;
		const row = Math.floor(i / cols);
		const cellW = colWidths[col];
		const cellH = rowHeights[row];
		const x = anchorX + colOffsets[col] + Math.round((cellW - sizes[i].width) / 2);
		const y = anchorY + rowOffsets[row] + Math.round((cellH - sizes[i].height) / 2);
		positions.push({
			x: Math.round(x),
			y: Math.round(y)
		});
	}
	return positions;
}
/** 由批量落点坐标与尺寸计算轴对齐包围盒（可加 margin 便于视口聚焦留边） */
function getPlacementBoundingBox(positions, sizes, margin = 16) {
	if (!positions.length || positions.length !== sizes.length) return null;
	let minLeft = Infinity;
	let minTop = Infinity;
	let maxRight = -Infinity;
	let maxBottom = -Infinity;
	for (let i = 0; i < positions.length; i += 1) {
		const { x, y } = positions[i];
		const w = sizes[i].width;
		const h = sizes[i].height;
		minLeft = Math.min(minLeft, x);
		minTop = Math.min(minTop, y);
		maxRight = Math.max(maxRight, x + w);
		maxBottom = Math.max(maxBottom, y + h);
	}
	const m = Math.max(0, margin);
	return {
		minLeft: minLeft - m,
		minTop: minTop - m,
		maxRight: maxRight + m,
		maxBottom: maxBottom + m
	};
}
//#endregion
export { computeBatchScenePlacementPositions, getPlacementBoundingBox };
