// Copyright (c) 2017 Kiel University and others.
// Copyright (c) 2026 The elk-go Authors.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0.
//
// SPDX-License-Identifier: EPL-2.0

package spore

import (
	

	
)

func growTree( *tree) bool {
	 := false
	var  func(*tree)
	 = func( *tree) {
		for ,  := range .children {
			.node.translate(.node.vertex.Sub(.node.original.point))
			 := overlap(.node.rect, .node.rect)
			if  > 1 {
				 = true
			}
			.node.setCenterPosition(.node.vertex.Add(
				.node.original.point.Sub(.node.original.point).Scale(),
			))
			()
		}
	}
	()
	return 
}

func compactTree( *tree,  bool) {
	var  func(*tree)
	 = func( *tree) {
		for ,  := range .children {
			()
		}
		for ,  := range .children {
			 := .node.vertex.Sub(.node.vertex)
			if  {
				,  := .node.rect, .node.rect
				if math.Abs(.X) >= math.Abs(.Y) {
					.Y = 0
					if .Y+.Height > .Y && .Y < .Y+.Height {
						 := math.Max(
							.X-(.X+.Width),
							.X-(.X+.Width),
						)
						 = sporeScaleToLength(, )
					}
				} else {
					.X = 0
					if .X+.Width > .X && .X < .X+.Width {
						 := math.Max(
							.Y-(.Y+.Height),
							.Y-(.Y+.Height),
						)
						 = sporeScaleToLength(, )
					}
				}
			} else {
				 = sporeScaleToLength(, .node.underlap(.node))
			}
			 := getMinUnderlap(, , sporeVectorLength(), )
			 = sporeScaleToLength(, )
			translateSubtree(, )
		}
	}
	()
}

func getMinUnderlap(,  *tree,  float64,  geometry.Point) float64 {
	 := math.Min(, minUnderlapWithSubtree(.node, , , ))
	for ,  := range .children {
		if  !=  {
			 = math.Min(, (, , , ))
		}
	}
	return 
}

func minUnderlapWithSubtree( *node,  *tree,  float64,  geometry.Point) float64 {
	 := 
	for ,  := range .children {
		 := .node
		if .touches() {
			if fuzzyCompare(.rect.X, .rect.X+.rect.Width, fuzziness) == 0 && .X < 0 ||
				fuzzyCompare(.rect.X+.rect.Width, .rect.X, fuzziness) == 0 && .X > 0 ||
				fuzzyCompare(.rect.Y, .rect.Y+.rect.Height, fuzziness) == 0 && .Y < 0 ||
				fuzzyCompare(.rect.Y+.rect.Height, .rect.Y, fuzziness) == 0 && .Y > 0 {
				 = 0
				break
			}
		} else {
			 = math.Min(, .distance(, ))
		}
		 = math.Min(, (, , , ))
	}
	return 
}

func translateSubtree( *tree,  geometry.Point) {
	.node.translate()
	for ,  := range .children {
		(, )
	}
}