package rtree

import (
	"math"
	"math/bits"
	"unsafe"
)

const (
	maxEntries    = 16
	minEntries    = 6
	sentinelCoord = int32(1 << 29)
	maxDist       = int64(1 << 42)
)

// node holds up to M=16 entries in Structure-of-Arrays layout aligned to
// 384 bytes (3 x 128-byte Apple M3 cache lines):
//   - Cache line 0 (bytes   0..127): x0, x1
//   - Cache line 1 (bytes 128..255): y0, y1
//   - Cache line 2 (bytes 256..383): val (child index or entry id), count
//
// Unused slots [count..15] hold sentinelCoord in x0 and x1 so Search, Remove,
// and Nearest can scan cache line 0 without reading count or touching lines 1-2
// when no entry qualifies. Containing no pointers, []node is noscan for Go's GC.
type node struct {
	x0    [maxEntries]int32
	x1    [maxEntries]int32
	y0    [maxEntries]int32
	y1    [maxEntries]int32
	val   [maxEntries]int32
	count int32 // also next-free index when on the free list
	_pad  [15]int32
}

// Compile-time check that sizeof(node) == 384 (3 * 128-byte cache lines).
var (
	_ [384 - unsafe.Sizeof(node{})]byte
	_ [unsafe.Sizeof(node{}) - 384]byte
)

var sentinelRow = [maxEntries]int32{
	sentinelCoord, sentinelCoord, sentinelCoord, sentinelCoord,
	sentinelCoord, sentinelCoord, sentinelCoord, sentinelCoord,
	sentinelCoord, sentinelCoord, sentinelCoord, sentinelCoord,
	sentinelCoord, sentinelCoord, sentinelCoord, sentinelCoord,
}

type pqItem struct {
	key  uint64 // (uint64(dist) << 4) | uint64(level)
	node int32
	_pad int32
}

type resItem struct {
	dist int64
	id   int32
	_pad int32
}

type reinsertItem struct {
	x0, y0, x1, y1, val int32
	level               int32
}

// RTree is a classic Guttman (1984) R-tree with M=16, m=6, and quadratic split.
type RTree struct {
	nodes       []node
	root        int32
	freeHead    int32
	count       int
	height      int
	nodeCount   int
	pq          []pqItem
	res         []resItem
	searchStack [256]uint64
	reinsert    [64]reinsertItem
}

// New creates an empty R-tree.
func New() *RTree {
	return &RTree{
		root:     -1,
		freeHead: -1,
	}
}

// Len returns the number of stored entries.
func (t *RTree) Len() int { return t.count }

// Height returns the number of levels in the tree (0 when empty).
func (t *RTree) Height() int { return t.height }

// NodeCount returns the number of live nodes in the tree (0 when empty).
func (t *RTree) NodeCount() int { return t.nodeCount }

func nodeAt(base *node, idx int32) *node {
	return (*node)(unsafe.Add(unsafe.Pointer(base), uintptr(idx)*384))
}

func (t *RTree) allocNode() int32 {
	t.nodeCount++
	if t.freeHead >= 0 {
		idx := t.freeHead
		n := &t.nodes[idx]
		t.freeHead = n.count
		n.x0 = sentinelRow
		n.x1 = sentinelRow
		n.count = 0
		return idx
	}
	idx := int32(len(t.nodes))
	if int(idx) == cap(t.nodes) {
		newCap := cap(t.nodes) * 2
		if newCap < 32 {
			newCap = 32
		}
		newNodes := make([]node, idx+1, newCap)
		copy(newNodes, t.nodes)
		t.nodes = newNodes
	} else {
		t.nodes = t.nodes[:idx+1]
	}
	n := &t.nodes[idx]
	n.x0 = sentinelRow
	n.x1 = sentinelRow
	n.count = 0
	return idx
}

func (t *RTree) freeNode(idx int32) {
	t.nodes[idx].count = t.freeHead
	t.freeHead = idx
	t.nodeCount--
}

// Insert adds (x0, y0, x1, y1, id) to the R-tree using Guttman's Insert and quadratic split.
func (t *RTree) Insert(x0, y0, x1, y1, id int32) {
	t.count++
	if t.height == 0 {
		r := t.allocNode()
		n := &t.nodes[r]
		n.x0[0], n.y0[0], n.x1[0], n.y1[0], n.val[0] = x0, y0, x1, y1, id
		n.count = 1
		t.root = r
		t.height = 1
		return
	}
	t.insertAtLevel(x0, y0, x1, y1, id, 0)
}

// insertAtLevel inserts an entry at targetLevel (0 = leaf, 1 = parent of leaf, ...).
func (t *RTree) insertAtLevel(rx0, ry0, rx1, ry1, rval int32, targetLevel int) {
	var pathNode [16]int32
	var pathSlot [16]int32

	cur := t.root
	base := unsafe.SliceData(t.nodes)

	// 1. Choose subtree down to targetLevel, expanding MBRs on the way down.
	// Expanding on the way down keeps the non-splitting fast path (~90% of inserts)
	// strictly one pass with zero upward traversal, and when a split is absorbed at
	// some parent, all ancestors above already have exact MBRs (MBR(old) U R).
	for lvl := t.height - 1; lvl > targetLevel; lvl-- {
		n := nodeAt(base, cur)
		cnt := int(n.count)
		if cnt > maxEntries {
			cnt = maxEntries
		}

		nx0, nx1 := &n.x0, &n.x1
		ny0, ny1 := &n.y0, &n.y1

		bx0, bx1 := nx0[0], nx1[0]
		by0, by1 := ny0[0], ny1[0]
		bestArea := int64(bx1-bx0) * int64(by1-by0)
		bestEnl := int64(max(bx1, rx1)-min(bx0, rx0))*int64(max(by1, ry1)-min(by0, ry0)) - bestArea
		best := 0

		if bestEnl != 0 || bestArea != 0 {
			for i := 1; i < cnt; i++ {
				bx0, bx1 = nx0[i], nx1[i]
				by0, by1 = ny0[i], ny1[i]
				area := int64(bx1-bx0) * int64(by1-by0)
				enl := int64(max(bx1, rx1)-min(bx0, rx0))*int64(max(by1, ry1)-min(by0, ry0)) - area
				if enl < bestEnl || (enl == bestEnl && area < bestArea) {
					bestEnl = enl
					bestArea = area
					best = i
					if bestEnl == 0 && bestArea == 0 {
						break
					}
				}
			}
		}

		// Expand chosen child's MBR in-place only when needed (keeps clean cache lines).
		if rx0 < nx0[best] {
			nx0[best] = rx0
		}
		if ry0 < ny0[best] {
			ny0[best] = ry0
		}
		if rx1 > nx1[best] {
			nx1[best] = rx1
		}
		if ry1 > ny1[best] {
			ny1[best] = ry1
		}

		pathNode[lvl] = cur
		pathSlot[lvl] = int32(best)
		cur = n.val[best]
	}

	// 2. Insert into target node; fast path if it has room.
	leaf := nodeAt(base, cur)
	c := leaf.count
	if c < maxEntries {
		leaf.x0[c], leaf.y0[c], leaf.x1[c], leaf.y1[c], leaf.val[c] = rx0, ry0, rx1, ry1, rval
		leaf.count = c + 1
		return
	}

	// 3. Split and propagate upward (allocNode may reallocate t.nodes, so index t.nodes directly).
	newIdx, g1x0, g1y0, g1x1, g1y1, g2x0, g2y0, g2x1, g2y1 := t.splitNode(cur, rx0, ry0, rx1, ry1, rval)

	for lvl := targetLevel + 1; lvl < t.height; lvl++ {
		pIdx := pathNode[lvl]
		slot := pathSlot[lvl]
		p := &t.nodes[pIdx]
		// Update existing child's exact MBR from split.
		p.x0[slot], p.y0[slot], p.x1[slot], p.y1[slot] = g1x0, g1y0, g1x1, g1y1

		pc := p.count
		if pc < maxEntries {
			// Parent absorbs the split; all ancestors above already have exact MBRs.
			p.x0[pc], p.y0[pc], p.x1[pc], p.y1[pc], p.val[pc] = g2x0, g2y0, g2x1, g2y1, newIdx
			p.count = pc + 1
			return
		}
		newIdx, g1x0, g1y0, g1x1, g1y1, g2x0, g2y0, g2x1, g2y1 = t.splitNode(pIdx, g2x0, g2y0, g2x1, g2y1, newIdx)
	}

	// 4. Root split: allocate a new root holding both halves.
	oldRoot := t.root
	newRoot := t.allocNode()
	r := &t.nodes[newRoot]
	r.x0[0], r.y0[0], r.x1[0], r.y1[0], r.val[0] = g1x0, g1y0, g1x1, g1y1, oldRoot
	r.x0[1], r.y0[1], r.x1[1], r.y1[1], r.val[1] = g2x0, g2y0, g2x1, g2y1, newIdx
	r.count = 2
	t.root = newRoot
	t.height++
}

// splitNode performs Guttman's quadratic split of nodeIdx's 16 entries plus
// (rx0, ry0, rx1, ry1, rval) into nodeIdx (group 1) and a newly allocated node (group 2).
// Returns the new node index and the exact bounding rectangles of both groups.
func (t *RTree) splitNode(nodeIdx, rx0, ry0, rx1, ry1, rval int32) (
	newIdx int32,
	g1x0, g1y0, g1x1, g1y1 int32,
	g2x0, g2y0, g2x1, g2y1 int32,
) {
	newIdx = t.allocNode()
	n1 := &t.nodes[nodeIdx]
	n2 := &t.nodes[newIdx]

	var sx0, sx1, sy0, sy1, sval [17]int32
	copy(sx0[:16], n1.x0[:])
	copy(sx1[:16], n1.x1[:])
	copy(sy0[:16], n1.y0[:])
	copy(sy1[:16], n1.y1[:])
	copy(sval[:16], n1.val[:])
	sx0[16], sy0[16], sx1[16], sy1[16], sval[16] = rx0, ry0, rx1, ry1, rval

	var area [17]int64
	for i := 0; i < 17; i++ {
		area[i] = int64(sx1[i]-sx0[i]) * int64(sy1[i]-sy0[i])
	}

	// PickSeeds: maximize area(J) - area(E1) - area(E2).
	bestD := int64(math.MinInt64)
	seed1, seed2 := 0, 1
	for i := 0; i < 16; i++ {
		ix0, iy0, ix1, iy1 := sx0[i], sy0[i], sx1[i], sy1[i]
		ia := area[i]
		for j := i + 1; j < 17; j++ {
			d := int64(max(ix1, sx1[j])-min(ix0, sx0[j]))*int64(max(iy1, sy1[j])-min(iy0, sy0[j])) - ia - area[j]
			if d > bestD {
				bestD = d
				seed1 = i
				seed2 = j
			}
		}
	}

	g1x0, g1y0, g1x1, g1y1 = sx0[seed1], sy0[seed1], sx1[seed1], sy1[seed1]
	g1Area := area[seed1]
	n1.x0[0], n1.y0[0], n1.x1[0], n1.y1[0], n1.val[0] = g1x0, g1y0, g1x1, g1y1, sval[seed1]
	c1 := int32(1)

	g2x0, g2y0, g2x1, g2y1 = sx0[seed2], sy0[seed2], sx1[seed2], sy1[seed2]
	g2Area := area[seed2]
	n2.x0[0], n2.y0[0], n2.x1[0], n2.y1[0], n2.val[0] = g2x0, g2y0, g2x1, g2y1, sval[seed2]
	c2 := int32(1)

	var rem [15]int
	remN := 0
	var d1, d2 [17]int64
	for i := 0; i < 17; i++ {
		if i == seed1 || i == seed2 {
			continue
		}
		rem[remN] = i
		remN++
		d1[i] = int64(max(g1x1, sx1[i])-min(g1x0, sx0[i]))*int64(max(g1y1, sy1[i])-min(g1y0, sy0[i])) - g1Area
		d2[i] = int64(max(g2x1, sx1[i])-min(g2x0, sx0[i]))*int64(max(g2y1, sy1[i])-min(g2y0, sy0[i])) - g2Area
	}

	for remN > 0 {
		if int(c1)+remN == minEntries {
			for k := 0; k < remN; k++ {
				e := rem[k]
				ex0, ey0, ex1, ey1 := sx0[e], sy0[e], sx1[e], sy1[e]
				n1.x0[c1], n1.y0[c1], n1.x1[c1], n1.y1[c1], n1.val[c1] = ex0, ey0, ex1, ey1, sval[e]
				c1++
				if ex0 < g1x0 {
					g1x0 = ex0
				}
				if ey0 < g1y0 {
					g1y0 = ey0
				}
				if ex1 > g1x1 {
					g1x1 = ex1
				}
				if ey1 > g1y1 {
					g1y1 = ey1
				}
			}
			break
		}
		if int(c2)+remN == minEntries {
			for k := 0; k < remN; k++ {
				e := rem[k]
				ex0, ey0, ex1, ey1 := sx0[e], sy0[e], sx1[e], sy1[e]
				n2.x0[c2], n2.y0[c2], n2.x1[c2], n2.y1[c2], n2.val[c2] = ex0, ey0, ex1, ey1, sval[e]
				c2++
				if ex0 < g2x0 {
					g2x0 = ex0
				}
				if ey0 < g2y0 {
					g2y0 = ey0
				}
				if ex1 > g2x1 {
					g2x1 = ex1
				}
				if ey1 > g2y1 {
					g2y1 = ey1
				}
			}
			break
		}

		// PickNext: entry maximizing |d1 - d2|.
		bestPos := 0
		bestDiff := int64(-1)
		for k := 0; k < remN; k++ {
			e := rem[k]
			diff := d1[e] - d2[e]
			if diff < 0 {
				diff = -diff
			}
			if diff > bestDiff {
				bestDiff = diff
				bestPos = k
			}
		}

		e := rem[bestPos]
		remN--
		rem[bestPos] = rem[remN]

		e1, e2 := d1[e], d2[e]
		toGroup1 := e1 < e2 || (e1 == e2 && (g1Area < g2Area || (g1Area == g2Area && c1 <= c2)))
		ex0, ey0, ex1, ey1 := sx0[e], sy0[e], sx1[e], sy1[e]

		if toGroup1 {
			n1.x0[c1], n1.y0[c1], n1.x1[c1], n1.y1[c1], n1.val[c1] = ex0, ey0, ex1, ey1, sval[e]
			c1++
			if ex0 < g1x0 || ey0 < g1y0 || ex1 > g1x1 || ey1 > g1y1 {
				if ex0 < g1x0 {
					g1x0 = ex0
				}
				if ey0 < g1y0 {
					g1y0 = ey0
				}
				if ex1 > g1x1 {
					g1x1 = ex1
				}
				if ey1 > g1y1 {
					g1y1 = ey1
				}
				g1Area = int64(g1x1-g1x0) * int64(g1y1-g1y0)
				for k := 0; k < remN; k++ {
					r := rem[k]
					d1[r] = int64(max(g1x1, sx1[r])-min(g1x0, sx0[r]))*int64(max(g1y1, sy1[r])-min(g1y0, sy0[r])) - g1Area
				}
			}
		} else {
			n2.x0[c2], n2.y0[c2], n2.x1[c2], n2.y1[c2], n2.val[c2] = ex0, ey0, ex1, ey1, sval[e]
			c2++
			if ex0 < g2x0 || ey0 < g2y0 || ex1 > g2x1 || ey1 > g2y1 {
				if ex0 < g2x0 {
					g2x0 = ex0
				}
				if ey0 < g2y0 {
					g2y0 = ey0
				}
				if ex1 > g2x1 {
					g2x1 = ex1
				}
				if ey1 > g2y1 {
					g2y1 = ey1
				}
				g2Area = int64(g2x1-g2x0) * int64(g2y1-g2y0)
				for k := 0; k < remN; k++ {
					r := rem[k]
					d2[r] = int64(max(g2x1, sx1[r])-min(g2x0, sx0[r]))*int64(max(g2y1, sy1[r])-min(g2y0, sy0[r])) - g2Area
				}
			}
		}
	}

	n1.count = c1
	for i := c1; i < maxEntries; i++ {
		n1.x0[i] = sentinelCoord
		n1.x1[i] = sentinelCoord
	}
	// n2 already has sentinelCoord in [c2..15] from allocNode.
	n2.count = c2
	return
}

func recomputeMBR(n *node) (bx0, by0, bx1, by1 int32) {
	cnt := int(n.count)
	if cnt > maxEntries {
		cnt = maxEntries
	}
	nx0, nx1 := &n.x0, &n.x1
	ny0, ny1 := &n.y0, &n.y1
	bx0, bx1 = nx0[0], nx1[0]
	by0, by1 = ny0[0], ny1[0]
	for i := 1; i < cnt; i++ {
		if nx0[i] < bx0 {
			bx0 = nx0[i]
		}
		if nx1[i] > bx1 {
			bx1 = nx1[i]
		}
		if ny0[i] < by0 {
			by0 = ny0[i]
		}
		if ny1[i] > by1 {
			by1 = ny1[i]
		}
	}
	return
}

// containsMask returns a 16-bit mask of entries in n whose MBR contains [rx0,rx1] x [ry0,ry1].
func containsMask(n *node, rx0, ry0, rx1, ry1 int32) uint16 {
	x0, x1 := &n.x0, &n.x1
	m0 := ((uint32((rx0-x0[0])|(x1[0]-rx1)) >> 31) << 0) |
		((uint32((rx0-x0[1])|(x1[1]-rx1)) >> 31) << 1) |
		((uint32((rx0-x0[2])|(x1[2]-rx1)) >> 31) << 2) |
		((uint32((rx0-x0[3])|(x1[3]-rx1)) >> 31) << 3)
	m1 := ((uint32((rx0-x0[4])|(x1[4]-rx1)) >> 31) << 4) |
		((uint32((rx0-x0[5])|(x1[5]-rx1)) >> 31) << 5) |
		((uint32((rx0-x0[6])|(x1[6]-rx1)) >> 31) << 6) |
		((uint32((rx0-x0[7])|(x1[7]-rx1)) >> 31) << 7)
	m2 := ((uint32((rx0-x0[8])|(x1[8]-rx1)) >> 31) << 8) |
		((uint32((rx0-x0[9])|(x1[9]-rx1)) >> 31) << 9) |
		((uint32((rx0-x0[10])|(x1[10]-rx1)) >> 31) << 10) |
		((uint32((rx0-x0[11])|(x1[11]-rx1)) >> 31) << 11)
	m3 := ((uint32((rx0-x0[12])|(x1[12]-rx1)) >> 31) << 12) |
		((uint32((rx0-x0[13])|(x1[13]-rx1)) >> 31) << 13) |
		((uint32((rx0-x0[14])|(x1[14]-rx1)) >> 31) << 14) |
		((uint32((rx0-x0[15])|(x1[15]-rx1)) >> 31) << 15)
	mask := uint16(^(m0 | m1 | m2 | m3))
	if mask == 0 {
		return 0
	}
	y0, y1 := &n.y0, &n.y1
	out := uint16(0)
	for m := mask; m != 0; m &= m - 1 {
		i := bits.TrailingZeros16(m)
		if y0[i] <= ry0 && ry1 <= y1[i] {
			out |= 1 << uint(i)
		}
	}
	return out
}

func findInLeaf(n *node, rx0, ry0, rx1, ry1, id int32) int32 {
	x0, x1 := &n.x0, &n.x1
	for i := 0; i < maxEntries; i++ {
		if ((x0[i] ^ rx0) | (x1[i] ^ rx1)) == 0 {
			if n.y0[i] == ry0 && n.y1[i] == ry1 && n.val[i] == id {
				return int32(i)
			}
		}
	}
	return -1
}

// Remove deletes the entry with exact rectangle (rx0, ry0, rx1, ry1) and id,
// condensing underfull nodes and shrinking bounding rectangles per Guttman (1984).
func (t *RTree) Remove(rx0, ry0, rx1, ry1, id int32) bool {
	if t.height == 0 {
		return false
	}
	base := unsafe.SliceData(t.nodes)

	if t.height == 1 {
		leaf := nodeAt(base, t.root)
		slot := findInLeaf(leaf, rx0, ry0, rx1, ry1, id)
		if slot < 0 {
			return false
		}
		t.count--
		if t.count == 0 {
			t.freeNode(t.root)
			t.root = -1
			t.height = 0
			return true
		}
		last := leaf.count - 1
		leaf.count = last
		if slot != last {
			leaf.x0[slot] = leaf.x0[last]
			leaf.x1[slot] = leaf.x1[last]
			leaf.y0[slot] = leaf.y0[last]
			leaf.y1[slot] = leaf.y1[last]
			leaf.val[slot] = leaf.val[last]
		}
		leaf.x0[last] = sentinelCoord
		leaf.x1[last] = sentinelCoord
		return true
	}

	// 1. FindLeaf via iterative DFS backtracking, keeping the exact path on stack.
	var pathNode [16]int32
	var pathSlot [16]int32
	var pathMask [16]uint16

	topLvl := t.height - 1
	pathNode[topLvl] = t.root
	pathMask[topLvl] = containsMask(nodeAt(base, t.root), rx0, ry0, rx1, ry1)

	lvl := topLvl
	leafSlot := int32(-1)
	for {
		m := pathMask[lvl]
		if m == 0 {
			lvl++
			if lvl > topLvl {
				return false
			}
			continue
		}
		slot := bits.TrailingZeros16(m)
		pathMask[lvl] = m & (m - 1)
		pathSlot[lvl] = int32(slot)

		child := nodeAt(base, pathNode[lvl]).val[slot]
		if lvl == 1 {
			leaf := nodeAt(base, child)
			if s := findInLeaf(leaf, rx0, ry0, rx1, ry1, id); s >= 0 {
				pathNode[0] = child
				leafSlot = s
				break
			}
		} else {
			cm := containsMask(nodeAt(base, child), rx0, ry0, rx1, ry1)
			if cm != 0 {
				lvl--
				pathNode[lvl] = child
				pathMask[lvl] = cm
			}
		}
	}

	// 2. Remove entry from leaf.
	leaf := nodeAt(base, pathNode[0])
	last := leaf.count - 1
	leaf.count = last
	if leafSlot != last {
		leaf.x0[leafSlot] = leaf.x0[last]
		leaf.x1[leafSlot] = leaf.x1[last]
		leaf.y0[leafSlot] = leaf.y0[last]
		leaf.y1[leafSlot] = leaf.y1[last]
		leaf.val[leafSlot] = leaf.val[last]
	}
	leaf.x0[last] = sentinelCoord
	leaf.x1[last] = sentinelCoord
	t.count--

	// 3. CondenseTree from leaf up to (but not including) root.
	reinsCount := 0
	childRemoved := true
	oldX0, oldY0, oldX1, oldY1 := rx0, ry0, rx1, ry1
	var newX0, newY0, newX1, newY1 int32

	for cl := 0; cl < topLvl; cl++ {
		nIdx := pathNode[cl]
		n := nodeAt(base, nIdx)
		pIdx := pathNode[cl+1]
		p := nodeAt(base, pIdx)
		pSlot := pathSlot[cl+1]

		if n.count < minEntries {
			// Save old MBR of removed child n in p before overwriting pSlot.
			oldX0, oldY0, oldX1, oldY1 = p.x0[pSlot], p.y0[pSlot], p.x1[pSlot], p.y1[pSlot]

			// Remove n from p via swap-with-last.
			pLast := p.count - 1
			p.count = pLast
			if pSlot != pLast {
				p.x0[pSlot] = p.x0[pLast]
				p.x1[pSlot] = p.x1[pLast]
				p.y0[pSlot] = p.y0[pLast]
				p.y1[pSlot] = p.y1[pLast]
				p.val[pSlot] = p.val[pLast]
			}
			p.x0[pLast] = sentinelCoord
			p.x1[pLast] = sentinelCoord

			// Set aside remaining entries of n with their level.
			nc := n.count
			for i := int32(0); i < nc; i++ {
				t.reinsert[reinsCount] = reinsertItem{
					x0:    n.x0[i],
					y0:    n.y0[i],
					x1:    n.x1[i],
					y1:    n.y1[i],
					val:   n.val[i],
					level: int32(cl),
				}
				reinsCount++
			}
			t.freeNode(nIdx)
			childRemoved = true
			continue
		}

		// Node n did not underflow: shrink its MBR in p only if a boundary edge could move.
		px0, py0, px1, py1 := p.x0[pSlot], p.y0[pSlot], p.x1[pSlot], p.y1[pSlot]
		var mayShrink bool
		if childRemoved {
			mayShrink = oldX0 == px0 || oldY0 == py0 || oldX1 == px1 || oldY1 == py1
		} else {
			mayShrink = (oldX0 == px0 && newX0 > px0) ||
				(oldY0 == py0 && newY0 > py0) ||
				(oldX1 == px1 && newX1 < px1) ||
				(oldY1 == py1 && newY1 < py1)
		}
		if !mayShrink {
			break
		}
		nx0, ny0, nx1, ny1 := recomputeMBR(n)
		if nx0 == px0 && ny0 == py0 && nx1 == px1 && ny1 == py1 {
			break
		}
		p.x0[pSlot], p.y0[pSlot], p.x1[pSlot], p.y1[pSlot] = nx0, ny0, nx1, ny1
		oldX0, oldY0, oldX1, oldY1 = px0, py0, px1, py1
		newX0, newY0, newX1, newY1 = nx0, ny0, nx1, ny1
		childRemoved = false
	}

	// Reinsert set-aside entries (highest level first).
	for i := reinsCount - 1; i >= 0; i-- {
		e := t.reinsert[i]
		t.insertAtLevel(e.x0, e.y0, e.x1, e.y1, e.val, int(e.level))
	}

	// 4. Shrink root if it is an internal node with a single child.
	for t.height > 1 && t.nodes[t.root].count == 1 {
		oldRoot := t.root
		t.root = t.nodes[oldRoot].val[0]
		t.freeNode(oldRoot)
		t.height--
	}

	return true
}

// Search finds all stored entries intersecting [qx0, qx1] x [qy0, qy1], writes up to
// len(outIDs) of their ids into outIDs, and returns the total number of matches.
func (t *RTree) Search(qx0, qy0, qx1, qy1 int32, outIDs []int32) int {
	if t.height == 0 {
		return 0
	}
	if qx0 == qx1 && qy0 == qy1 {
		return t.searchPoint(qx0, qy0, outIDs)
	}

	base := unsafe.SliceData(t.nodes)
	capOut := len(outIDs)
	total := 0

	if t.height == 1 {
		leaf := nodeAt(base, t.root)
		lx0, lx1 := &leaf.x0, &leaf.x1
		m0 := ((uint32((qx1-lx0[0])|(lx1[0]-qx0)) >> 31) << 0) |
			((uint32((qx1-lx0[1])|(lx1[1]-qx0)) >> 31) << 1) |
			((uint32((qx1-lx0[2])|(lx1[2]-qx0)) >> 31) << 2) |
			((uint32((qx1-lx0[3])|(lx1[3]-qx0)) >> 31) << 3)
		m1 := ((uint32((qx1-lx0[4])|(lx1[4]-qx0)) >> 31) << 4) |
			((uint32((qx1-lx0[5])|(lx1[5]-qx0)) >> 31) << 5) |
			((uint32((qx1-lx0[6])|(lx1[6]-qx0)) >> 31) << 6) |
			((uint32((qx1-lx0[7])|(lx1[7]-qx0)) >> 31) << 7)
		m2 := ((uint32((qx1-lx0[8])|(lx1[8]-qx0)) >> 31) << 8) |
			((uint32((qx1-lx0[9])|(lx1[9]-qx0)) >> 31) << 9) |
			((uint32((qx1-lx0[10])|(lx1[10]-qx0)) >> 31) << 10) |
			((uint32((qx1-lx0[11])|(lx1[11]-qx0)) >> 31) << 11)
		m3 := ((uint32((qx1-lx0[12])|(lx1[12]-qx0)) >> 31) << 12) |
			((uint32((qx1-lx0[13])|(lx1[13]-qx0)) >> 31) << 13) |
			((uint32((qx1-lx0[14])|(lx1[14]-qx0)) >> 31) << 14) |
			((uint32((qx1-lx0[15])|(lx1[15]-qx0)) >> 31) << 15)
		mask := uint16(^(m0 | m1 | m2 | m3))
		if mask != 0 {
			ly0, ly1, lval := &leaf.y0, &leaf.y1, &leaf.val
			for mask != 0 {
				j := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if ly0[j] <= qy1 && qy0 <= ly1[j] {
					if total < capOut {
						outIDs[total] = lval[j]
					}
					total++
				}
			}
		}
		return total
	}

	stack := &t.searchStack
	stack[0] = (uint64(t.root) << 8) | uint64(t.height-1)
	sp := 1

	for sp > 0 {
		sp--
		entry := stack[sp]
		lvl := int(entry & 0x7F)
		n := nodeAt(base, int32(entry>>8))

		// Contained subtree fast path: bit 7 set -> skip coordinate cache lines 0 & 1!
		if (entry & 0x80) != 0 {
			cnt := int(n.count)
			if cnt > maxEntries {
				cnt = maxEntries
			}
			nval := &n.val
			if lvl == 1 {
				for i := 0; i < cnt; i++ {
					leaf := nodeAt(base, nval[i])
					lc := int(leaf.count)
					if uint(total) < uint(capOut) {
						copy(outIDs[total:], leaf.val[:lc])
					}
					total += lc
				}
			} else {
				childTag := uint64(lvl-1) | 0x80
				for i := 0; i < cnt; i++ {
					stack[sp] = (uint64(nval[i]) << 8) | childTag
					sp++
				}
			}
			continue
		}

		// Branchless 4-way X-interval intersection filter on cache line 0 only.
		x0, x1 := &n.x0, &n.x1
		m0 := ((uint32((qx1-x0[0])|(x1[0]-qx0)) >> 31) << 0) |
			((uint32((qx1-x0[1])|(x1[1]-qx0)) >> 31) << 1) |
			((uint32((qx1-x0[2])|(x1[2]-qx0)) >> 31) << 2) |
			((uint32((qx1-x0[3])|(x1[3]-qx0)) >> 31) << 3)
		m1 := ((uint32((qx1-x0[4])|(x1[4]-qx0)) >> 31) << 4) |
			((uint32((qx1-x0[5])|(x1[5]-qx0)) >> 31) << 5) |
			((uint32((qx1-x0[6])|(x1[6]-qx0)) >> 31) << 6) |
			((uint32((qx1-x0[7])|(x1[7]-qx0)) >> 31) << 7)
		m2 := ((uint32((qx1-x0[8])|(x1[8]-qx0)) >> 31) << 8) |
			((uint32((qx1-x0[9])|(x1[9]-qx0)) >> 31) << 9) |
			((uint32((qx1-x0[10])|(x1[10]-qx0)) >> 31) << 10) |
			((uint32((qx1-x0[11])|(x1[11]-qx0)) >> 31) << 11)
		m3 := ((uint32((qx1-x0[12])|(x1[12]-qx0)) >> 31) << 12) |
			((uint32((qx1-x0[13])|(x1[13]-qx0)) >> 31) << 13) |
			((uint32((qx1-x0[14])|(x1[14]-qx0)) >> 31) << 14) |
			((uint32((qx1-x0[15])|(x1[15]-qx0)) >> 31) << 15)
		mask := uint16(^(m0 | m1 | m2 | m3))
		if mask == 0 {
			continue
		}

		y0, y1, val := &n.y0, &n.y1, &n.val
		if lvl > 1 {
			childLvl := uint64(lvl - 1)
			for mask != 0 {
				i := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if y0[i] <= qy1 && qy0 <= y1[i] {
					tag := childLvl
					if ((x0[i] - qx0) | (qx1 - x1[i]) | (y0[i] - qy0) | (qy1 - y1[i])) >= 0 {
						tag |= 0x80
					}
					stack[sp] = (uint64(val[i]) << 8) | tag
					sp++
				}
			}
		} else {
			// Children are leaves: scan directly without pushing onto stack.
			for mask != 0 {
				i := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if y0[i] <= qy1 && qy0 <= y1[i] {
					leaf := nodeAt(base, val[i])
					if ((x0[i] - qx0) | (qx1 - x1[i]) | (y0[i] - qy0) | (qy1 - y1[i])) >= 0 {
						lc := int(leaf.count)
						if uint(total) < uint(capOut) {
							copy(outIDs[total:], leaf.val[:lc])
						}
						total += lc
						continue
					}
					lx0, lx1 := &leaf.x0, &leaf.x1
					lm0 := ((uint32((qx1-lx0[0])|(lx1[0]-qx0)) >> 31) << 0) |
						((uint32((qx1-lx0[1])|(lx1[1]-qx0)) >> 31) << 1) |
						((uint32((qx1-lx0[2])|(lx1[2]-qx0)) >> 31) << 2) |
						((uint32((qx1-lx0[3])|(lx1[3]-qx0)) >> 31) << 3)
					lm1 := ((uint32((qx1-lx0[4])|(lx1[4]-qx0)) >> 31) << 4) |
						((uint32((qx1-lx0[5])|(lx1[5]-qx0)) >> 31) << 5) |
						((uint32((qx1-lx0[6])|(lx1[6]-qx0)) >> 31) << 6) |
						((uint32((qx1-lx0[7])|(lx1[7]-qx0)) >> 31) << 7)
					lm2 := ((uint32((qx1-lx0[8])|(lx1[8]-qx0)) >> 31) << 8) |
						((uint32((qx1-lx0[9])|(lx1[9]-qx0)) >> 31) << 9) |
						((uint32((qx1-lx0[10])|(lx1[10]-qx0)) >> 31) << 10) |
						((uint32((qx1-lx0[11])|(lx1[11]-qx0)) >> 31) << 11)
					lm3 := ((uint32((qx1-lx0[12])|(lx1[12]-qx0)) >> 31) << 12) |
						((uint32((qx1-lx0[13])|(lx1[13]-qx0)) >> 31) << 13) |
						((uint32((qx1-lx0[14])|(lx1[14]-qx0)) >> 31) << 14) |
						((uint32((qx1-lx0[15])|(lx1[15]-qx0)) >> 31) << 15)
					lmask := uint16(^(lm0 | lm1 | lm2 | lm3))
					if lmask == 0 {
						continue
					}
					ly0, ly1, lval := &leaf.y0, &leaf.y1, &leaf.val
					for lmask != 0 {
						j := bits.TrailingZeros16(lmask)
						lmask &= lmask - 1
						if ly0[j] <= qy1 && qy0 <= ly1[j] {
							if total < capOut {
								outIDs[total] = lval[j]
							}
							total++
						}
					}
				}
			}
		}
	}
	return total
}

func (t *RTree) searchPoint(qx, qy int32, outIDs []int32) int {
	base := unsafe.SliceData(t.nodes)
	capOut := len(outIDs)
	total := 0

	if t.height == 1 {
		leaf := nodeAt(base, t.root)
		lx0, lx1 := &leaf.x0, &leaf.x1
		m0 := ((uint32((qx-lx0[0])|(lx1[0]-qx)) >> 31) << 0) |
			((uint32((qx-lx0[1])|(lx1[1]-qx)) >> 31) << 1) |
			((uint32((qx-lx0[2])|(lx1[2]-qx)) >> 31) << 2) |
			((uint32((qx-lx0[3])|(lx1[3]-qx)) >> 31) << 3)
		m1 := ((uint32((qx-lx0[4])|(lx1[4]-qx)) >> 31) << 4) |
			((uint32((qx-lx0[5])|(lx1[5]-qx)) >> 31) << 5) |
			((uint32((qx-lx0[6])|(lx1[6]-qx)) >> 31) << 6) |
			((uint32((qx-lx0[7])|(lx1[7]-qx)) >> 31) << 7)
		m2 := ((uint32((qx-lx0[8])|(lx1[8]-qx)) >> 31) << 8) |
			((uint32((qx-lx0[9])|(lx1[9]-qx)) >> 31) << 9) |
			((uint32((qx-lx0[10])|(lx1[10]-qx)) >> 31) << 10) |
			((uint32((qx-lx0[11])|(lx1[11]-qx)) >> 31) << 11)
		m3 := ((uint32((qx-lx0[12])|(lx1[12]-qx)) >> 31) << 12) |
			((uint32((qx-lx0[13])|(lx1[13]-qx)) >> 31) << 13) |
			((uint32((qx-lx0[14])|(lx1[14]-qx)) >> 31) << 14) |
			((uint32((qx-lx0[15])|(lx1[15]-qx)) >> 31) << 15)
		mask := uint16(^(m0 | m1 | m2 | m3))
		if mask != 0 {
			ly0, ly1, lval := &leaf.y0, &leaf.y1, &leaf.val
			for mask != 0 {
				j := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if ly0[j] <= qy && qy <= ly1[j] {
					if total < capOut {
						outIDs[total] = lval[j]
					}
					total++
				}
			}
		}
		return total
	}

	stack := &t.searchStack
	stack[0] = (uint64(t.root) << 8) | uint64(t.height-1)
	sp := 1

	for sp > 0 {
		sp--
		entry := stack[sp]
		lvl := int(entry & 0x7F)
		n := nodeAt(base, int32(entry>>8))

		x0, x1 := &n.x0, &n.x1
		m0 := ((uint32((qx-x0[0])|(x1[0]-qx)) >> 31) << 0) |
			((uint32((qx-x0[1])|(x1[1]-qx)) >> 31) << 1) |
			((uint32((qx-x0[2])|(x1[2]-qx)) >> 31) << 2) |
			((uint32((qx-x0[3])|(x1[3]-qx)) >> 31) << 3)
		m1 := ((uint32((qx-x0[4])|(x1[4]-qx)) >> 31) << 4) |
			((uint32((qx-x0[5])|(x1[5]-qx)) >> 31) << 5) |
			((uint32((qx-x0[6])|(x1[6]-qx)) >> 31) << 6) |
			((uint32((qx-x0[7])|(x1[7]-qx)) >> 31) << 7)
		m2 := ((uint32((qx-x0[8])|(x1[8]-qx)) >> 31) << 8) |
			((uint32((qx-x0[9])|(x1[9]-qx)) >> 31) << 9) |
			((uint32((qx-x0[10])|(x1[10]-qx)) >> 31) << 10) |
			((uint32((qx-x0[11])|(x1[11]-qx)) >> 31) << 11)
		m3 := ((uint32((qx-x0[12])|(x1[12]-qx)) >> 31) << 12) |
			((uint32((qx-x0[13])|(x1[13]-qx)) >> 31) << 13) |
			((uint32((qx-x0[14])|(x1[14]-qx)) >> 31) << 14) |
			((uint32((qx-x0[15])|(x1[15]-qx)) >> 31) << 15)
		mask := uint16(^(m0 | m1 | m2 | m3))
		if mask == 0 {
			continue
		}

		y0, y1, val := &n.y0, &n.y1, &n.val
		if lvl > 1 {
			childLvl := uint64(lvl - 1)
			for mask != 0 {
				i := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if y0[i] <= qy && qy <= y1[i] {
					stack[sp] = (uint64(val[i]) << 8) | childLvl
					sp++
				}
			}
		} else {
			for mask != 0 {
				i := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if y0[i] <= qy && qy <= y1[i] {
					leaf := nodeAt(base, val[i])
					lx0, lx1 := &leaf.x0, &leaf.x1
					lm0 := ((uint32((qx-lx0[0])|(lx1[0]-qx)) >> 31) << 0) |
						((uint32((qx-lx0[1])|(lx1[1]-qx)) >> 31) << 1) |
						((uint32((qx-lx0[2])|(lx1[2]-qx)) >> 31) << 2) |
						((uint32((qx-lx0[3])|(lx1[3]-qx)) >> 31) << 3)
					lm1 := ((uint32((qx-lx0[4])|(lx1[4]-qx)) >> 31) << 4) |
						((uint32((qx-lx0[5])|(lx1[5]-qx)) >> 31) << 5) |
						((uint32((qx-lx0[6])|(lx1[6]-qx)) >> 31) << 6) |
						((uint32((qx-lx0[7])|(lx1[7]-qx)) >> 31) << 7)
					lm2 := ((uint32((qx-lx0[8])|(lx1[8]-qx)) >> 31) << 8) |
						((uint32((qx-lx0[9])|(lx1[9]-qx)) >> 31) << 9) |
						((uint32((qx-lx0[10])|(lx1[10]-qx)) >> 31) << 10) |
						((uint32((qx-lx0[11])|(lx1[11]-qx)) >> 31) << 11)
					lm3 := ((uint32((qx-lx0[12])|(lx1[12]-qx)) >> 31) << 12) |
						((uint32((qx-lx0[13])|(lx1[13]-qx)) >> 31) << 13) |
						((uint32((qx-lx0[14])|(lx1[14]-qx)) >> 31) << 14) |
						((uint32((qx-lx0[15])|(lx1[15]-qx)) >> 31) << 15)
					lmask := uint16(^(lm0 | lm1 | lm2 | lm3))
					if lmask == 0 {
						continue
					}
					ly0, ly1, lval := &leaf.y0, &leaf.y1, &leaf.val
					for lmask != 0 {
						j := bits.TrailingZeros16(lmask)
						lmask &= lmask - 1
						if ly0[j] <= qy && qy <= ly1[j] {
							if total < capOut {
								outIDs[total] = lval[j]
							}
							total++
						}
					}
				}
			}
		}
	}
	return total
}

// 4-ary min-heap helpers for Nearest's best-first priority queue.
func pqPush(pq []pqItem, item pqItem) []pqItem {
	i := len(pq)
	pq = append(pq, item)
	for i > 0 {
		p := (i - 1) >> 2
		if pq[p].key <= item.key {
			break
		}
		pq[i] = pq[p]
		i = p
	}
	pq[i] = item
	return pq
}

func pqPop(pq []pqItem) (pqItem, []pqItem) {
	top := pq[0]
	last := len(pq) - 1
	item := pq[last]
	pq = pq[:last]
	if last > 0 {
		i := 0
		for {
			c := (i << 2) + 1
			if c >= last {
				break
			}
			minC := c
			minK := pq[c].key
			if c+3 < last {
				if k := pq[c+1].key; k < minK {
					minK = k
					minC = c + 1
				}
				if k := pq[c+2].key; k < minK {
					minK = k
					minC = c + 2
				}
				if k := pq[c+3].key; k < minK {
					minK = k
					minC = c + 3
				}
			} else {
				for j := c + 1; j < last; j++ {
					if k := pq[j].key; k < minK {
						minK = k
						minC = j
					}
				}
			}
			if item.key <= minK {
				break
			}
			pq[i] = pq[minC]
			i = minC
		}
		pq[i] = item
	}
	return top, pq
}

// Binary max-heap helpers for Nearest's top-k result buffer, ordered by
// (dist DESC, id DESC) so res[0] is always the worst of the k best entries.
func resGreater(a, b resItem) bool {
	return a.dist > b.dist || (a.dist == b.dist && a.id > b.id)
}

func siftDownMax(h []resItem, i int) {
	n := len(h)
	item := h[i]
	for {
		c := (i << 1) + 1
		if c >= n {
			break
		}
		if c+1 < n && resGreater(h[c+1], h[c]) {
			c++
		}
		if !resGreater(h[c], item) {
			break
		}
		h[i] = h[c]
		i = c
	}
	h[i] = item
}

func heapifyMax(h []resItem) {
	for i := len(h)/2 - 1; i >= 0; i-- {
		siftDownMax(h, i)
	}
}

// Nearest writes the ids of the min(k, Len()) entries nearest to (px, py)
// in ascending order of squared distance (and ascending id on ties).
func (t *RTree) Nearest(px, py int32, k int, outIDs []int32) int {
	if k <= 0 || t.count == 0 {
		return 0
	}
	want := k
	if want > t.count {
		want = t.count
	}
	if want == 1 {
		outIDs[0] = t.nearest1(px, py)
		return 1
	}

	base := unsafe.SliceData(t.nodes)
	pq := t.pq[:0]
	res := t.res[:0]
	if cap(res) < want {
		res = make([]resItem, 0, want)
	}

	boundDist := maxDist
	// Conservative integer radius R >= floor(sqrt(boundDist)) for branchless cache-line-0 X-filtering.
	boundR := int32(1 << 21)
	qx0, qx1 := px-boundR, px+boundR
	qy0, qy1 := py-boundR, py+boundR

	curNode := t.root
	curLevel := t.height - 1

	for {
		n := nodeAt(base, curNode)

		// Branchless 4-way X-interval filter [px-boundR, px+boundR] on cache line 0 only.
		x0, x1 := &n.x0, &n.x1
		m0 := ((uint32((qx1-x0[0])|(x1[0]-qx0)) >> 31) << 0) |
			((uint32((qx1-x0[1])|(x1[1]-qx0)) >> 31) << 1) |
			((uint32((qx1-x0[2])|(x1[2]-qx0)) >> 31) << 2) |
			((uint32((qx1-x0[3])|(x1[3]-qx0)) >> 31) << 3)
		m1 := ((uint32((qx1-x0[4])|(x1[4]-qx0)) >> 31) << 4) |
			((uint32((qx1-x0[5])|(x1[5]-qx0)) >> 31) << 5) |
			((uint32((qx1-x0[6])|(x1[6]-qx0)) >> 31) << 6) |
			((uint32((qx1-x0[7])|(x1[7]-qx0)) >> 31) << 7)
		m2 := ((uint32((qx1-x0[8])|(x1[8]-qx0)) >> 31) << 8) |
			((uint32((qx1-x0[9])|(x1[9]-qx0)) >> 31) << 9) |
			((uint32((qx1-x0[10])|(x1[10]-qx0)) >> 31) << 10) |
			((uint32((qx1-x0[11])|(x1[11]-qx0)) >> 31) << 11)
		m3 := ((uint32((qx1-x0[12])|(x1[12]-qx0)) >> 31) << 12) |
			((uint32((qx1-x0[13])|(x1[13]-qx0)) >> 31) << 13) |
			((uint32((qx1-x0[14])|(x1[14]-qx0)) >> 31) << 14) |
			((uint32((qx1-x0[15])|(x1[15]-qx0)) >> 31) << 15)
		mask := uint16(^(m0 | m1 | m2 | m3))

		if curLevel == 0 {
			if mask != 0 {
				y0, y1, val := &n.y0, &n.y1, &n.val
				for mask != 0 {
					i := bits.TrailingZeros16(mask)
					mask &= mask - 1
					if y0[i] <= qy1 && qy0 <= y1[i] {
						dx := int64(max(max(x0[i]-px, px-x1[i]), 0))
						dy := int64(max(max(y0[i]-py, py-y1[i]), 0))
						d := dx*dx + dy*dy
						if d <= boundDist {
							id := val[i]
							if len(res) < want {
								res = append(res, resItem{dist: d, id: id})
								if len(res) == want {
									heapifyMax(res)
									boundDist = res[0].dist
									boundR = int32(math.Sqrt(float64(boundDist)))
									qx0, qx1 = px-boundR, px+boundR
									qy0, qy1 = py-boundR, py+boundR
								}
							} else if d < res[0].dist || (d == res[0].dist && id < res[0].id) {
								res[0] = resItem{dist: d, id: id}
								siftDownMax(res, 0)
								if res[0].dist < boundDist {
									boundDist = res[0].dist
									boundR = int32(math.Sqrt(float64(boundDist)))
									qx0, qx1 = px-boundR, px+boundR
									qy0, qy1 = py-boundR, py+boundR
								}
							}
						}
					}
				}
			}
			// Pop next best node from pq.
			if len(pq) == 0 || int64(pq[0].key>>4) > boundDist {
				break
			}
			var top pqItem
			top, pq = pqPop(pq)
			curNode = top.node
			curLevel = int(top.key & 15)
			continue
		}

		// Internal node: collect qualifying children (d <= boundDist), keeping bestChild
		// out of the heap to bypass push+pop when it is already <= pq[0].
		if mask != 0 {
			childLvl := uint64(curLevel - 1)
			bestD := maxDist + 1
			bestChild := int32(-1)
			y0, y1, val := &n.y0, &n.y1, &n.val
			for mask != 0 {
				i := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if y0[i] <= qy1 && qy0 <= y1[i] {
					dx := int64(max(max(x0[i]-px, px-x1[i]), 0))
					dy := int64(max(max(y0[i]-py, py-y1[i]), 0))
					d := dx*dx + dy*dy
					if d <= boundDist {
						child := val[i]
						if d < bestD {
							if bestChild >= 0 {
								pq = pqPush(pq, pqItem{key: (uint64(bestD) << 4) | childLvl, node: bestChild})
							}
							bestD = d
							bestChild = child
						} else {
							pq = pqPush(pq, pqItem{key: (uint64(d) << 4) | childLvl, node: child})
						}
					}
				}
			}

			if bestChild >= 0 {
				bestKey := (uint64(bestD) << 4) | childLvl
				if len(pq) == 0 || bestKey <= pq[0].key {
					curNode = bestChild
					curLevel = int(childLvl)
					continue
				}
				pq = pqPush(pq, pqItem{key: bestKey, node: bestChild})
			}
		}

		if len(pq) == 0 || int64(pq[0].key>>4) > boundDist {
			break
		}
		var top pqItem
		top, pq = pqPop(pq)
		curNode = top.node
		curLevel = int(top.key & 15)
	}

	// Extract results from max-heap in ascending (dist, id) order.
	for i := want - 1; i > 0; i-- {
		outIDs[i] = res[0].id
		res[0] = res[i]
		siftDownMax(res[:i], 0)
	}
	outIDs[0] = res[0].id

	t.pq = pq[:0]
	t.res = res[:0]
	return want
}

// nearest1 is a specialized fast path for k == 1 (zero result-heap overhead).
func (t *RTree) nearest1(px, py int32) int32 {
	base := unsafe.SliceData(t.nodes)
	pq := t.pq[:0]

	bestDist := maxDist
	bestID := int32(math.MaxInt32)
	boundR := int32(1 << 21)
	qx0, qx1 := px-boundR, px+boundR
	qy0, qy1 := py-boundR, py+boundR

	curNode := t.root
	curLevel := t.height - 1

	for {
		n := nodeAt(base, curNode)

		x0, x1 := &n.x0, &n.x1
		m0 := ((uint32((qx1-x0[0])|(x1[0]-qx0)) >> 31) << 0) |
			((uint32((qx1-x0[1])|(x1[1]-qx0)) >> 31) << 1) |
			((uint32((qx1-x0[2])|(x1[2]-qx0)) >> 31) << 2) |
			((uint32((qx1-x0[3])|(x1[3]-qx0)) >> 31) << 3)
		m1 := ((uint32((qx1-x0[4])|(x1[4]-qx0)) >> 31) << 4) |
			((uint32((qx1-x0[5])|(x1[5]-qx0)) >> 31) << 5) |
			((uint32((qx1-x0[6])|(x1[6]-qx0)) >> 31) << 6) |
			((uint32((qx1-x0[7])|(x1[7]-qx0)) >> 31) << 7)
		m2 := ((uint32((qx1-x0[8])|(x1[8]-qx0)) >> 31) << 8) |
			((uint32((qx1-x0[9])|(x1[9]-qx0)) >> 31) << 9) |
			((uint32((qx1-x0[10])|(x1[10]-qx0)) >> 31) << 10) |
			((uint32((qx1-x0[11])|(x1[11]-qx0)) >> 31) << 11)
		m3 := ((uint32((qx1-x0[12])|(x1[12]-qx0)) >> 31) << 12) |
			((uint32((qx1-x0[13])|(x1[13]-qx0)) >> 31) << 13) |
			((uint32((qx1-x0[14])|(x1[14]-qx0)) >> 31) << 14) |
			((uint32((qx1-x0[15])|(x1[15]-qx0)) >> 31) << 15)
		mask := uint16(^(m0 | m1 | m2 | m3))

		if curLevel == 0 {
			if mask != 0 {
				y0, y1, val := &n.y0, &n.y1, &n.val
				for mask != 0 {
					i := bits.TrailingZeros16(mask)
					mask &= mask - 1
					if y0[i] <= qy1 && qy0 <= y1[i] {
						dx := int64(max(max(x0[i]-px, px-x1[i]), 0))
						dy := int64(max(max(y0[i]-py, py-y1[i]), 0))
						d := dx*dx + dy*dy
						if d < bestDist {
							bestDist = d
							bestID = val[i]
							boundR = int32(math.Sqrt(float64(bestDist)))
							qx0, qx1 = px-boundR, px+boundR
							qy0, qy1 = py-boundR, py+boundR
						} else if d == bestDist && val[i] < bestID {
							bestID = val[i]
						}
					}
				}
			}
			if len(pq) == 0 || int64(pq[0].key>>4) > bestDist {
				break
			}
			var top pqItem
			top, pq = pqPop(pq)
			curNode = top.node
			curLevel = int(top.key & 15)
			continue
		}

		if mask != 0 {
			childLvl := uint64(curLevel - 1)
			bestD := maxDist + 1
			bestChild := int32(-1)
			y0, y1, val := &n.y0, &n.y1, &n.val
			for mask != 0 {
				i := bits.TrailingZeros16(mask)
				mask &= mask - 1
				if y0[i] <= qy1 && qy0 <= y1[i] {
					dx := int64(max(max(x0[i]-px, px-x1[i]), 0))
					dy := int64(max(max(y0[i]-py, py-y1[i]), 0))
					d := dx*dx + dy*dy
					if d <= bestDist {
						child := val[i]
						if d < bestD {
							if bestChild >= 0 {
								pq = pqPush(pq, pqItem{key: (uint64(bestD) << 4) | childLvl, node: bestChild})
							}
							bestD = d
							bestChild = child
						} else {
							pq = pqPush(pq, pqItem{key: (uint64(d) << 4) | childLvl, node: child})
						}
					}
				}
			}

			if bestChild >= 0 {
				bestKey := (uint64(bestD) << 4) | childLvl
				if len(pq) == 0 || bestKey <= pq[0].key {
					curNode = bestChild
					curLevel = int(childLvl)
					continue
				}
				pq = pqPush(pq, pqItem{key: bestKey, node: bestChild})
			}
		}

		if len(pq) == 0 || int64(pq[0].key>>4) > bestDist {
			break
		}
		var top pqItem
		top, pq = pqPop(pq)
		curNode = top.node
		curLevel = int(top.key & 15)
	}

	t.pq = pq[:0]
	return bestID
}
