import { BoxDefinition } from '../types'

export function normalizeBoxes(boxes: BoxDefinition[]) {
	// TODO: This is not optimized at all
	for (let i = 0; i < boxes.length; i++) {
		const box = boxes[i]

		if (box.y > 0) {
			const above = boxes
				.filter(
					(b) =>
						b.id !== box.id &&
						b.x < box.x + box.w &&
						box.x < b.x + b.w &&
						b.y < box.y
				)
				.sort((a, b) => b.y - a.y)

			if (above.length === 0) {
				box.y = 0
				i = -1
			} else {
				const newY = above[0].h + above[0].y

				if (box.y !== newY) {
					box.y = newY
					i = -1
				}
			}
		}
	}

	return boxes
}
