const std = @import("std");
const Allocator = std.mem.Allocator;

const MAX_ENTRIES: usize = 16;
const MIN_ENTRIES: usize = 6;
const MAX_DEPTH: usize = 32;
const EMPTY_NODE: u32 = std.math.maxInt(u32);

// Sentinel coordinate for unused slots in a node's 16-entry bounding-box arrays.
// All valid coordinates are in [0, 2^20). With SENTINEL = -(1 << 22):
// - Intersection test (x0 <= qx1 && x1 >= qx0): x1 >= qx0 is always false.
// - Containment test (x0 <= rx0 && x1 >= rx1): x1 >= rx1 is always false.
// - Enlargement in chooseSubtree: old_area = 0, new_w >= 2^22, new_h >= 2^22 =>
//   enlargement >= 2^44, strictly greater than any valid enlargement (< 2^40).
// - Squared distance in nearest: dx >= 2^22, dy >= 2^22 => dist >= 2^45,
//   strictly greater than SENTINEL_CUTOFF (2^42) and any valid distance (< 2^41).
const SENTINEL: i32 = -(1 << 22);
const SENTINEL_CUTOFF: u64 = @as(u64, 1) << 42;

const V16i32 = @Vector(16, i32);
const V16i64 = @Vector(16, i64);
const V16u64 = @Vector(16, u64);
const V16u1 = @Vector(16, u1);
const V16u8 = @Vector(16, u8);
const V4i32 = @Vector(4, i32);
const V4i64 = @Vector(4, i64);

const IDX_VEC: V16u8 = .{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

// Exactly 256 bytes (2 x 128-byte Apple M3 cache lines), 128-byte aligned.
// Cache line 0 holds x0 and x1; cache line 1 holds y0 and y1.
// Queries that fail the X-axis check skip loading cache line 1 entirely.
const NodeBoxes = struct {
    x0: [MAX_ENTRIES]i32 align(128),
    x1: [MAX_ENTRIES]i32,
    y0: [MAX_ENTRIES]i32,
    y1: [MAX_ENTRIES]i32,
};

// 64 bytes (half a 128-byte cache line), 64-byte aligned so a node's payload
// array never straddles a cache line. Holds child node indices (as u32 bitcast)
// for internal nodes, or entry ids for leaves.
const NodeVals = struct {
    v: [MAX_ENTRIES]i32 align(64),
};

const Rect = struct {
    x0: i32,
    y0: i32,
    x1: i32,
    y1: i32,
};

const SplitResult = struct {
    left_box: Rect,
    right_node: u32,
    right_box: Rect,
};

const ReinsertEntry = struct {
    x0: i32,
    y0: i32,
    x1: i32,
    y1: i32,
    val: i32,
    level: u8,
};

const SearchFrame = struct {
    node: u32,
    level: u8,
};

const HeapItem = struct {
    dist: u64,
    node: u32,
    level: u8,
};

const KItem = struct {
    dist: u64,
    id: i32,

    inline fn isBetter(a: KItem, b: KItem) bool {
        return a.dist < b.dist or (a.dist == b.dist and a.id < b.id);
    }

    inline fn isWorse(a: KItem, b: KItem) bool {
        return a.dist > b.dist or (a.dist == b.dist and a.id > b.id);
    }
};

pub const RTree = struct {
    allocator: Allocator,

    // Pool-level SoA node storage.
    boxes: []NodeBoxes,
    vals: []NodeVals,
    counts: []u8,
    pool_len: u32,
    pool_cap: u32,
    free_head: u32,

    root: u32,
    tree_height: u8,
    entry_count: usize,
    active_nodes: usize,

    // Reusable scratch space for nearest() (4-ary min-heap + large-k max-heap).
    nn_heap: []HeapItem,
    nn_kbuf: []KItem,

    pub fn init(allocator: Allocator) RTree {
        return .{
            .allocator = allocator,
            .boxes = &.{},
            .vals = &.{},
            .counts = &.{},
            .pool_len = 0,
            .pool_cap = 0,
            .free_head = EMPTY_NODE,
            .root = EMPTY_NODE,
            .tree_height = 0,
            .entry_count = 0,
            .active_nodes = 0,
            .nn_heap = &.{},
            .nn_kbuf = &.{},
        };
    }

    pub fn deinit(self: *RTree) void {
        if (self.boxes.len > 0) self.allocator.free(self.boxes);
        if (self.vals.len > 0) self.allocator.free(self.vals);
        if (self.counts.len > 0) self.allocator.free(self.counts);
        if (self.nn_heap.len > 0) self.allocator.free(self.nn_heap);
        if (self.nn_kbuf.len > 0) self.allocator.free(self.nn_kbuf);
        self.* = init(self.allocator);
    }

    pub inline fn len(self: *const RTree) usize {
        return self.entry_count;
    }

    pub inline fn height(self: *const RTree) usize {
        return self.tree_height;
    }

    pub inline fn nodeCount(self: *const RTree) usize {
        return self.active_nodes;
    }

    // --------------------------------------------------------- pool management

    fn growPool(self: *RTree, min_needed: u32) Allocator.Error!void {
        @branchHint(.cold);
        var new_cap: u32 = if (self.pool_cap == 0) 64 else self.pool_cap * 2;
        while (new_cap < min_needed) {
            new_cap *= 2;
        }
        if (self.pool_cap == 0) {
            const new_boxes = try self.allocator.alloc(NodeBoxes, new_cap);
            errdefer self.allocator.free(new_boxes);
            const new_vals = try self.allocator.alloc(NodeVals, new_cap);
            errdefer self.allocator.free(new_vals);
            const new_counts = try self.allocator.alloc(u8, new_cap);
            self.boxes = new_boxes;
            self.vals = new_vals;
            self.counts = new_counts;
        } else {
            self.boxes = try self.allocator.realloc(self.boxes, new_cap);
            self.vals = try self.allocator.realloc(self.vals, new_cap);
            self.counts = try self.allocator.realloc(self.counts, new_cap);
        }
        self.pool_cap = new_cap;
    }

    inline fn ensureFreeNodes(self: *RTree, extra: u32) Allocator.Error!void {
        if (self.free_head == EMPTY_NODE and self.pool_len + extra > self.pool_cap) {
            try self.growPool(self.pool_len + extra);
        }
    }

    inline fn allocNode(self: *RTree) Allocator.Error!u32 {
        var idx: u32 = undefined;
        if (self.free_head != EMPTY_NODE) {
            idx = self.free_head;
            self.free_head = @bitCast(self.vals[idx].v[0]);
        } else {
            if (self.pool_len == self.pool_cap) {
                try self.growPool(self.pool_len + 1);
            }
            idx = self.pool_len;
            self.pool_len += 1;
        }
        self.active_nodes += 1;
        return idx;
    }

    inline fn freeNode(self: *RTree, idx: u32) void {
        self.vals[idx].v[0] = @bitCast(self.free_head);
        self.free_head = idx;
        self.active_nodes -= 1;
    }

    inline fn fillSentinels(b: *NodeBoxes, from: usize) void {
        for (from..MAX_ENTRIES) |i| {
            b.x0[i] = SENTINEL;
            b.x1[i] = SENTINEL;
            b.y0[i] = SENTINEL;
            b.y1[i] = SENTINEL;
        }
    }

    inline fn initFreshNode(self: *RTree, idx: u32) void {
        const b = &self.boxes[idx];
        const s: V16i32 = @splat(SENTINEL);
        b.x0 = s;
        b.x1 = s;
        b.y0 = s;
        b.y1 = s;
        self.counts[idx] = 0;
    }

    inline fn removeSlot(self: *RTree, node: u32, slot: usize) void {
        const last: usize = @as(usize, self.counts[node]) - 1;
        self.counts[node] = @intCast(last);
        const b = &self.boxes[node];
        const v = &self.vals[node];
        if (slot != last) {
            b.x0[slot] = b.x0[last];
            b.x1[slot] = b.x1[last];
            b.y0[slot] = b.y0[last];
            b.y1[slot] = b.y1[last];
            v.v[slot] = v.v[last];
        }
        b.x0[last] = SENTINEL;
        b.x1[last] = SENTINEL;
        b.y0[last] = SENTINEL;
        b.y1[last] = SENTINEL;
    }

    inline fn computeNodeBbox(self: *const RTree, node: u32) Rect {
        const b = &self.boxes[node];
        const c = self.counts[node];
        const valid = IDX_VEC < @as(V16u8, @splat(c));
        const inf_v: V16i32 = @splat(std.math.maxInt(i32));
        return .{
            .x0 = @reduce(.Min, @select(i32, valid, @as(V16i32, b.x0), inf_v)),
            .y0 = @reduce(.Min, @select(i32, valid, @as(V16i32, b.y0), inf_v)),
            .x1 = @reduce(.Max, @as(V16i32, b.x1)),
            .y1 = @reduce(.Max, @as(V16i32, b.y1)),
        };
    }

    // --------------------------------------------------------------- insertion

    pub fn insert(self: *RTree, x0: i32, y0: i32, x1: i32, y1: i32, id: i32) Allocator.Error!void {
        if (self.tree_height == 0) {
            const r = try self.allocNode();
            self.initFreshNode(r);
            const b = &self.boxes[r];
            b.x0[0] = x0;
            b.x1[0] = x1;
            b.y0[0] = y0;
            b.y1[0] = y1;
            self.vals[r].v[0] = id;
            self.counts[r] = 1;
            self.root = r;
            self.tree_height = 1;
            self.entry_count = 1;
            return;
        }
        try self.insertAtLevel(x0, y0, x1, y1, id, 0);
        self.entry_count += 1;
    }

    inline fn chooseSubtree(b: *const NodeBoxes, rx0: i32, ry0: i32, rx1: i32, ry1: i32) usize {
        const vx0: V16i32 = b.x0;
        const vx1: V16i32 = b.x1;
        const vy0: V16i32 = b.y0;
        const vy1: V16i32 = b.y1;

        const old_w: V16i64 = vx1 - vx0;
        const old_h: V16i64 = vy1 - vy0;
        const new_w: V16i64 = @max(vx1, @as(V16i32, @splat(rx1))) - @min(vx0, @as(V16i32, @splat(rx0)));
        const new_h: V16i64 = @max(vy1, @as(V16i32, @splat(ry1))) - @min(vy0, @as(V16i32, @splat(ry0)));

        const old_area: V16i64 = old_w * old_h;
        const enl: V16i64 = new_w * new_h - old_area;

        const min_enl: i64 = @reduce(.Min, enl);
        const tie_mask: u16 = @bitCast(enl == @as(V16i64, @splat(min_enl)));
        const first: usize = @ctz(tie_mask);
        var rem = tie_mask & (tie_mask - 1);
        if (rem == 0) return first;

        const areas: [MAX_ENTRIES]i64 = old_area;
        var best_i: usize = first;
        var best_area: i64 = areas[first];
        while (rem != 0) {
            const i: usize = @ctz(rem);
            rem &= rem - 1;
            if (areas[i] < best_area) {
                best_area = areas[i];
                best_i = i;
            }
        }
        return best_i;
    }

    fn insertAtLevel(self: *RTree, rx0: i32, ry0: i32, rx1: i32, ry1: i32, rval: i32, target_level: u8) Allocator.Error!void {
        // Pre-ensure enough pool capacity for worst-case full-path split + new root,
        // so optimistic downward bbox updates cannot be aborted by OOM.
        try self.ensureFreeNodes(@as(u32, self.tree_height) + 2);

        var path_node: [MAX_DEPTH]u32 = undefined;
        var path_slot: [MAX_DEPTH]u8 = undefined;

        var cur: u32 = self.root;
        var lvl: u8 = self.tree_height - 1;

        while (lvl > target_level) {
            const b = &self.boxes[cur];
            const best_i = chooseSubtree(b, rx0, ry0, rx1, ry1);

            // Optimistically expand the chosen child's bounding box on the way down.
            // If no split occurs (or once a split is absorbed), every ancestor above
            // already holds its exact bounding rectangle.
            if (rx0 < b.x0[best_i] or rx1 > b.x1[best_i] or ry0 < b.y0[best_i] or ry1 > b.y1[best_i]) {
                b.x0[best_i] = @min(b.x0[best_i], rx0);
                b.x1[best_i] = @max(b.x1[best_i], rx1);
                b.y0[best_i] = @min(b.y0[best_i], ry0);
                b.y1[best_i] = @max(b.y1[best_i], ry1);
            }

            path_node[lvl] = cur;
            path_slot[lvl] = @intCast(best_i);
            cur = @bitCast(self.vals[cur].v[best_i]);
            lvl -= 1;
        }

        const c: usize = self.counts[cur];
        if (c < MAX_ENTRIES) {
            const b = &self.boxes[cur];
            b.x0[c] = rx0;
            b.x1[c] = rx1;
            b.y0[c] = ry0;
            b.y1[c] = ry1;
            self.vals[cur].v[c] = rval;
            self.counts[cur] = @intCast(c + 1);
            return;
        }

        // Slow path: split cur and propagate splits upward.
        var split = try self.splitNode(cur, rx0, ry0, rx1, ry1, rval);
        var cur_lvl: u8 = target_level;

        while (cur_lvl + 1 < self.tree_height) {
            const parent = path_node[cur_lvl + 1];
            const slot: usize = path_slot[cur_lvl + 1];
            const pb = &self.boxes[parent];

            // Update left half's exact bounding box in parent.
            pb.x0[slot] = split.left_box.x0;
            pb.x1[slot] = split.left_box.x1;
            pb.y0[slot] = split.left_box.y0;
            pb.y1[slot] = split.left_box.y1;

            const pc: usize = self.counts[parent];
            if (pc < MAX_ENTRIES) {
                pb.x0[pc] = split.right_box.x0;
                pb.x1[pc] = split.right_box.x1;
                pb.y0[pc] = split.right_box.y0;
                pb.y1[pc] = split.right_box.y1;
                self.vals[parent].v[pc] = @bitCast(split.right_node);
                self.counts[parent] = @intCast(pc + 1);
                return;
            }

            split = try self.splitNode(
                parent,
                split.right_box.x0,
                split.right_box.y0,
                split.right_box.x1,
                split.right_box.y1,
                @bitCast(split.right_node),
            );
            cur_lvl += 1;
        }

        // The root split: create a new root holding the two halves.
        const old_root = self.root;
        const new_root = try self.allocNode();
        self.initFreshNode(new_root);
        const rb = &self.boxes[new_root];
        rb.x0[0] = split.left_box.x0;
        rb.x1[0] = split.left_box.x1;
        rb.y0[0] = split.left_box.y0;
        rb.y1[0] = split.left_box.y1;
        self.vals[new_root].v[0] = @bitCast(old_root);

        rb.x0[1] = split.right_box.x0;
        rb.x1[1] = split.right_box.x1;
        rb.y0[1] = split.right_box.y0;
        rb.y1[1] = split.right_box.y1;
        self.vals[new_root].v[1] = @bitCast(split.right_node);

        self.counts[new_root] = 2;
        self.root = new_root;
        self.tree_height += 1;
    }

    // Guttman's quadratic split of a full node (16 entries) + 1 new entry.
    fn splitNode(self: *RTree, node: u32, nx0: i32, ny0: i32, nx1: i32, ny1: i32, nval: i32) Allocator.Error!SplitResult {
        @branchHint(.cold);
        var ax0: [17]i32 = undefined;
        var ax1: [17]i32 = undefined;
        var ay0: [17]i32 = undefined;
        var ay1: [17]i32 = undefined;
        var aval: [17]i32 = undefined;
        var aarea: [17]i64 = undefined;

        {
            const b = &self.boxes[node];
            const v = &self.vals[node];
            ax0[0..16].* = b.x0;
            ax1[0..16].* = b.x1;
            ay0[0..16].* = b.y0;
            ay1[0..16].* = b.y1;
            aval[0..16].* = v.v;

            const vw: V16i64 = @as(V16i32, b.x1) - @as(V16i32, b.x0);
            const vh: V16i64 = @as(V16i32, b.y1) - @as(V16i32, b.y0);
            aarea[0..16].* = vw * vh;

            ax0[16] = nx0;
            ax1[16] = nx1;
            ay0[16] = ny0;
            ay1[16] = ny1;
            aval[16] = nval;
            aarea[16] = @as(i64, nx1 - nx0) * @as(i64, ny1 - ny0);
        }

        // 1. PickSeeds: find pair (i, j) with 0 <= i < j < 17 maximizing
        //    d = area(J(i, j)) - area(i) - area(j), vectorized in 4-wide chunks over j in 1..16.
        var best_d: i64 = std.math.minInt(i64);
        var seed0: usize = 0;
        var seed1: usize = 1;

        const min_i64_v: V4i64 = @splat(std.math.minInt(i64));
        const lane_offs = @Vector(4, i32){ 0, 1, 2, 3 };

        for (0..16) |i| {
            const ix0_v: V4i32 = @splat(ax0[i]);
            const ix1_v: V4i32 = @splat(ax1[i]);
            const iy0_v: V4i32 = @splat(ay0[i]);
            const iy1_v: V4i32 = @splat(ay1[i]);
            const iarea_v: V4i64 = @splat(aarea[i]);
            const i_i32: V4i32 = @splat(@intCast(i));

            const c_start: usize = i >> 2;
            var c: usize = c_start;
            while (c < 4) : (c += 1) {
                const j0: usize = (c << 2) + 1;
                const jx0: V4i32 = ax0[j0..][0..4].*;
                const jx1: V4i32 = ax1[j0..][0..4].*;
                const jy0: V4i32 = ay0[j0..][0..4].*;
                const jy1: V4i32 = ay1[j0..][0..4].*;
                const jarea: V4i64 = aarea[j0..][0..4].*;

                const jw: V4i64 = @max(ix1_v, jx1) - @min(ix0_v, jx0);
                const jh: V4i64 = @max(iy1_v, jy1) - @min(iy0_v, jy0);
                var d4: V4i64 = jw * jh - iarea_v - jarea;

                if (c == c_start) {
                    const j_idx = @as(V4i32, @splat(@intCast(j0))) + lane_offs;
                    d4 = @select(i64, j_idx > i_i32, d4, min_i64_v);
                }

                const cmax = @reduce(.Max, d4);
                if (cmax > best_d) {
                    const arr: [4]i64 = d4;
                    for (0..4) |lane| {
                        if (arr[lane] > best_d) {
                            best_d = arr[lane];
                            seed0 = i;
                            seed1 = j0 + lane;
                        }
                    }
                }
            }
        }

        // 2. Initialize groups with the two seeds and compact remaining 15 entries.
        var g0_x0 = ax0[seed0];
        var g0_x1 = ax1[seed0];
        var g0_y0 = ay0[seed0];
        var g0_y1 = ay1[seed0];
        var g0_area = aarea[seed0];

        var g1_x0 = ax0[seed1];
        var g1_x1 = ax1[seed1];
        var g1_y0 = ay0[seed1];
        var g1_y1 = ay1[seed1];
        var g1_area = aarea[seed1];

        var g0_idx: [MAX_ENTRIES]u8 = undefined;
        var g1_idx: [MAX_ENTRIES]u8 = undefined;
        g0_idx[0] = @intCast(seed0);
        g1_idx[0] = @intCast(seed1);
        var c0: usize = 1;
        var c1: usize = 1;

        var rem_x0: [MAX_ENTRIES]i32 = @splat(0);
        var rem_x1: [MAX_ENTRIES]i32 = @splat(0);
        var rem_y0: [MAX_ENTRIES]i32 = @splat(0);
        var rem_y1: [MAX_ENTRIES]i32 = @splat(0);
        var rem_id: [MAX_ENTRIES]u8 = undefined;
        var rem_d0: [MAX_ENTRIES]i64 = @splat(0);
        var rem_d1: [MAX_ENTRIES]i64 = @splat(0);
        var rem_len: usize = 0;

        for (0..17) |idx| {
            if (idx == seed0 or idx == seed1) continue;
            rem_x0[rem_len] = ax0[idx];
            rem_x1[rem_len] = ax1[idx];
            rem_y0[rem_len] = ay0[idx];
            rem_y1[rem_len] = ay1[idx];
            rem_id[rem_len] = @intCast(idx);
            rem_len += 1;
        }

        // 3. Distribute remaining entries using incremental vectorized PickNext.
        var g0_dirty = true;
        var g1_dirty = true;

        while (rem_len > 0) {
            if (c0 + rem_len == MIN_ENTRIES) {
                for (0..rem_len) |k| {
                    g0_idx[c0] = rem_id[k];
                    c0 += 1;
                    g0_x0 = @min(g0_x0, rem_x0[k]);
                    g0_x1 = @max(g0_x1, rem_x1[k]);
                    g0_y0 = @min(g0_y0, rem_y0[k]);
                    g0_y1 = @max(g0_y1, rem_y1[k]);
                }
                break;
            }
            if (c1 + rem_len == MIN_ENTRIES) {
                for (0..rem_len) |k| {
                    g1_idx[c1] = rem_id[k];
                    c1 += 1;
                    g1_x0 = @min(g1_x0, rem_x0[k]);
                    g1_x1 = @max(g1_x1, rem_x1[k]);
                    g1_y0 = @min(g1_y0, rem_y0[k]);
                    g1_y1 = @max(g1_y1, rem_y1[k]);
                }
                break;
            }

            if (g0_dirty) {
                const w: V16i64 = @max(@as(V16i32, rem_x1), @as(V16i32, @splat(g0_x1))) -
                    @min(@as(V16i32, rem_x0), @as(V16i32, @splat(g0_x0)));
                const h: V16i64 = @max(@as(V16i32, rem_y1), @as(V16i32, @splat(g0_y1))) -
                    @min(@as(V16i32, rem_y0), @as(V16i32, @splat(g0_y0)));
                rem_d0 = w * h - @as(V16i64, @splat(g0_area));
                g0_dirty = false;
            }
            if (g1_dirty) {
                const w: V16i64 = @max(@as(V16i32, rem_x1), @as(V16i32, @splat(g1_x1))) -
                    @min(@as(V16i32, rem_x0), @as(V16i32, @splat(g1_x0)));
                const h: V16i64 = @max(@as(V16i32, rem_y1), @as(V16i32, @splat(g1_y1))) -
                    @min(@as(V16i32, rem_y0), @as(V16i32, @splat(g1_y0)));
                rem_d1 = w * h - @as(V16i64, @splat(g1_area));
                g1_dirty = false;
            }

            const d0_v: V16i64 = rem_d0;
            const d1_v: V16i64 = rem_d1;
            const diff_v: V16i64 = @intCast(@abs(d0_v - d1_v));
            const valid = IDX_VEC < @as(V16u8, @splat(@intCast(rem_len)));
            const masked_diff = @select(i64, valid, diff_v, @as(V16i64, @splat(-1)));
            const max_diff: i64 = @reduce(.Max, masked_diff);
            const hit_mask: u16 = @bitCast(masked_diff == @as(V16i64, @splat(max_diff)));
            const best_k: usize = @ctz(hit_mask);

            const bd0 = rem_d0[best_k];
            const bd1 = rem_d1[best_k];
            const to_g0 = if (bd0 < bd1)
                true
            else if (bd1 < bd0)
                false
            else if (g0_area < g1_area)
                true
            else if (g1_area < g0_area)
                false
            else
                c0 <= c1;

            const ex0 = rem_x0[best_k];
            const ex1 = rem_x1[best_k];
            const ey0 = rem_y0[best_k];
            const ey1 = rem_y1[best_k];

            if (to_g0) {
                g0_idx[c0] = rem_id[best_k];
                c0 += 1;
                if (ex0 < g0_x0 or ex1 > g0_x1 or ey0 < g0_y0 or ey1 > g0_y1) {
                    g0_x0 = @min(g0_x0, ex0);
                    g0_x1 = @max(g0_x1, ex1);
                    g0_y0 = @min(g0_y0, ey0);
                    g0_y1 = @max(g0_y1, ey1);
                    g0_area = @as(i64, g0_x1 - g0_x0) * @as(i64, g0_y1 - g0_y0);
                    g0_dirty = true;
                }
            } else {
                g1_idx[c1] = rem_id[best_k];
                c1 += 1;
                if (ex0 < g1_x0 or ex1 > g1_x1 or ey0 < g1_y0 or ey1 > g1_y1) {
                    g1_x0 = @min(g1_x0, ex0);
                    g1_x1 = @max(g1_x1, ex1);
                    g1_y0 = @min(g1_y0, ey0);
                    g1_y1 = @max(g1_y1, ey1);
                    g1_area = @as(i64, g1_x1 - g1_x0) * @as(i64, g1_y1 - g1_y0);
                    g1_dirty = true;
                }
            }

            rem_len -= 1;
            if (best_k != rem_len) {
                rem_x0[best_k] = rem_x0[rem_len];
                rem_x1[best_k] = rem_x1[rem_len];
                rem_y0[best_k] = rem_y0[rem_len];
                rem_y1[best_k] = rem_y1[rem_len];
                rem_id[best_k] = rem_id[rem_len];
                rem_d0[best_k] = rem_d0[rem_len];
                rem_d1[best_k] = rem_d1[rem_len];
            }
        }

        // 4. Write group 0 back into `node`, group 1 into a newly allocated node.
        const right_node = try self.allocNode();

        const lb = &self.boxes[node];
        const lv = &self.vals[node];
        for (0..c0) |i| {
            const src = g0_idx[i];
            lb.x0[i] = ax0[src];
            lb.x1[i] = ax1[src];
            lb.y0[i] = ay0[src];
            lb.y1[i] = ay1[src];
            lv.v[i] = aval[src];
        }
        fillSentinels(lb, c0);
        self.counts[node] = @intCast(c0);

        const rb = &self.boxes[right_node];
        const rv = &self.vals[right_node];
        for (0..c1) |i| {
            const src = g1_idx[i];
            rb.x0[i] = ax0[src];
            rb.x1[i] = ax1[src];
            rb.y0[i] = ay0[src];
            rb.y1[i] = ay1[src];
            rv.v[i] = aval[src];
        }
        fillSentinels(rb, c1);
        self.counts[right_node] = @intCast(c1);

        return .{
            .left_box = .{ .x0 = g0_x0, .y0 = g0_y0, .x1 = g0_x1, .y1 = g0_y1 },
            .right_node = right_node,
            .right_box = .{ .x0 = g1_x0, .y0 = g1_y0, .x1 = g1_x1, .y1 = g1_y1 },
        };
    }

    // ----------------------------------------------------------------- removal

    fn findLeaf(
        self: *const RTree,
        node: u32,
        lvl: u8,
        rx0: i32,
        ry0: i32,
        rx1: i32,
        ry1: i32,
        id: i32,
        path_node: *[MAX_DEPTH]u32,
        path_slot: *[MAX_DEPTH]u8,
    ) bool {
        if (lvl == 0) {
            const c: u5 = @intCast(self.counts[node]);
            const valid_mask: u16 = @truncate((@as(u32, 1) << c) - 1);
            const vid: V16i32 = self.vals[node].v;
            const id_mask: u16 = @as(u16, @bitCast(vid == @as(V16i32, @splat(id)))) & valid_mask;
            if (id_mask != 0) {
                const i: usize = @ctz(id_mask);
                const b = &self.boxes[node];
                if (b.x0[i] == rx0 and b.x1[i] == rx1 and b.y0[i] == ry0 and b.y1[i] == ry1) {
                    path_node[0] = node;
                    path_slot[0] = @intCast(i);
                    return true;
                }
            }
            return false;
        }

        const b = &self.boxes[node];
        const x0_ok: V16u1 = @bitCast(@as(V16i32, b.x0) <= @as(V16i32, @splat(rx0)));
        const x1_ok: V16u1 = @bitCast(@as(V16i32, b.x1) >= @as(V16i32, @splat(rx1)));
        const x_mask: u16 = @bitCast(x0_ok & x1_ok);
        if (x_mask == 0) return false;

        const y0_ok: V16u1 = @bitCast(@as(V16i32, b.y0) <= @as(V16i32, @splat(ry0)));
        const y1_ok: V16u1 = @bitCast(@as(V16i32, b.y1) >= @as(V16i32, @splat(ry1)));
        var mask: u16 = x_mask & @as(u16, @bitCast(y0_ok & y1_ok));

        const children = &self.vals[node].v;
        while (mask != 0) {
            const i: usize = @ctz(mask);
            mask &= mask - 1;
            const child: u32 = @bitCast(children[i]);
            if (self.findLeaf(child, lvl - 1, rx0, ry0, rx1, ry1, id, path_node, path_slot)) {
                path_node[lvl] = node;
                path_slot[lvl] = @intCast(i);
                return true;
            }
        }
        return false;
    }

    pub fn remove(self: *RTree, rx0: i32, ry0: i32, rx1: i32, ry1: i32, id: i32) Allocator.Error!bool {
        if (self.tree_height == 0) return false;

        var path_node: [MAX_DEPTH]u32 = undefined;
        var path_slot: [MAX_DEPTH]u8 = undefined;

        if (!self.findLeaf(self.root, self.tree_height - 1, rx0, ry0, rx1, ry1, id, &path_node, &path_slot)) {
            return false;
        }

        self.entry_count -= 1;

        if (self.tree_height == 1) {
            self.removeSlot(self.root, path_slot[0]);
            if (self.counts[self.root] == 0) {
                self.freeNode(self.root);
                self.root = EMPTY_NODE;
                self.tree_height = 0;
            }
            return true;
        }

        // Remove entry from leaf.
        self.removeSlot(path_node[0], path_slot[0]);

        // CondenseTree: walk up from leaf to root's child.
        var reinsert_buf: [MAX_DEPTH * (MIN_ENTRIES - 1)]ReinsertEntry = undefined;
        var reinsert_len: usize = 0;

        var lvl: u8 = 0;
        const max_non_root_lvl: u8 = self.tree_height - 1;
        while (lvl < max_non_root_lvl) : (lvl += 1) {
            const cur = path_node[lvl];
            const parent = path_node[lvl + 1];
            const pslot: usize = path_slot[lvl + 1];

            if (self.counts[cur] < MIN_ENTRIES) {
                const cnt: usize = self.counts[cur];
                const b = &self.boxes[cur];
                const v = &self.vals[cur];
                for (0..cnt) |i| {
                    reinsert_buf[reinsert_len] = .{
                        .x0 = b.x0[i],
                        .y0 = b.y0[i],
                        .x1 = b.x1[i],
                        .y1 = b.y1[i],
                        .val = v.v[i],
                        .level = lvl,
                    };
                    reinsert_len += 1;
                }
                self.freeNode(cur);
                self.removeSlot(parent, pslot);
            } else {
                const pb = &self.boxes[parent];
                if (lvl == 0 and rx0 > pb.x0[pslot] and rx1 < pb.x1[pslot] and
                    ry0 > pb.y0[pslot] and ry1 < pb.y1[pslot])
                {
                    break;
                }
                const nb = self.computeNodeBbox(cur);
                if (nb.x0 == pb.x0[pslot] and nb.x1 == pb.x1[pslot] and
                    nb.y0 == pb.y0[pslot] and nb.y1 == pb.y1[pslot])
                {
                    break;
                }
                pb.x0[pslot] = nb.x0;
                pb.x1[pslot] = nb.x1;
                pb.y0[pslot] = nb.y0;
                pb.y1[pslot] = nb.y1;
            }
        }

        // Reinsert all set-aside entries at their original level (highest level first).
        var ri: usize = reinsert_len;
        while (ri > 0) {
            ri -= 1;
            const e = reinsert_buf[ri];
            try self.insertAtLevel(e.x0, e.y0, e.x1, e.y1, e.val, e.level);
        }

        // Shrink root while it is an internal node with a single child.
        while (self.tree_height > 1 and self.counts[self.root] == 1) {
            const old_root = self.root;
            self.root = @bitCast(self.vals[old_root].v[0]);
            self.freeNode(old_root);
            self.tree_height -= 1;
        }

        return true;
    }

    // ------------------------------------------------------------------ search

    // Dump all entries in a subtree whose bounding rectangle is completely
    // contained within the query window, touching only counts[] and vals[].
    fn collectSubtree(self: *const RTree, start_node: u32, start_level: u8, out_ids: []i32, total: *usize) void {
        var stack: [512]SearchFrame = undefined;
        var sp: usize = 0;
        stack[0] = .{ .node = start_node, .level = start_level };
        sp = 1;
        const cap = out_ids.len;

        while (sp > 0) {
            sp -= 1;
            const frame = stack[sp];
            const node = frame.node;
            const c: usize = self.counts[node];
            const vals = &self.vals[node].v;
            if (frame.level == 0) {
                const t = total.*;
                if (t < cap) {
                    const to_copy = @min(c, cap - t);
                    @memcpy(out_ids[t .. t + to_copy], vals[0..to_copy]);
                }
                total.* = t + c;
            } else {
                const child_lvl = frame.level - 1;
                for (0..c) |i| {
                    const child: u32 = @bitCast(vals[i]);
                    @prefetch(&self.vals[child], .{ .rw = .read, .locality = 1, .cache = .data });
                    stack[sp] = .{ .node = child, .level = child_lvl };
                    sp += 1;
                }
            }
        }
    }

    pub fn search(self: *const RTree, qx0: i32, qy0: i32, qx1: i32, qy1: i32, out_ids: []i32) usize {
        if (self.tree_height == 0) return 0;

        const qx0_v: V16i32 = @splat(qx0);
        const qx1_v: V16i32 = @splat(qx1);
        const qy0_v: V16i32 = @splat(qy0);
        const qy1_v: V16i32 = @splat(qy1);
        const cap = out_ids.len;
        var total: usize = 0;

        var stack: [512]SearchFrame = undefined;
        var sp: usize = 1;
        stack[0] = .{ .node = self.root, .level = self.tree_height - 1 };

        while (sp > 0) {
            sp -= 1;
            const frame = stack[sp];
            const node = frame.node;
            const b = &self.boxes[node];

            const x0_ok: V16u1 = @bitCast(@as(V16i32, b.x0) <= qx1_v);
            const x1_ok: V16u1 = @bitCast(@as(V16i32, b.x1) >= qx0_v);
            const x_mask: u16 = @bitCast(x0_ok & x1_ok);
            if (x_mask == 0) continue;

            const y0_ok: V16u1 = @bitCast(@as(V16i32, b.y0) <= qy1_v);
            const y1_ok: V16u1 = @bitCast(@as(V16i32, b.y1) >= qy0_v);
            var mask: u16 = x_mask & @as(u16, @bitCast(y0_ok & y1_ok));
            if (mask == 0) continue;

            const vals = &self.vals[node].v;
            if (frame.level == 0) {
                const hits: usize = @popCount(mask);
                if (total + hits <= cap) {
                    while (mask != 0) {
                        const i: usize = @ctz(mask);
                        mask &= mask - 1;
                        out_ids[total] = vals[i];
                        total += 1;
                    }
                } else {
                    const prev = total;
                    while (mask != 0 and total < cap) {
                        const i: usize = @ctz(mask);
                        mask &= mask - 1;
                        out_ids[total] = vals[i];
                        total += 1;
                    }
                    total = prev + hits;
                }
            } else if (frame.level == 1) {
                while (mask != 0) {
                    const i: usize = @ctz(mask);
                    mask &= mask - 1;
                    const child: u32 = @bitCast(vals[i]);
                    // If the query fully contains this leaf's MBR, dump its ids directly
                    // without loading boxes[child].
                    if (qx0 <= b.x0[i] and b.x1[i] <= qx1 and qy0 <= b.y0[i] and b.y1[i] <= qy1) {
                        const c: usize = self.counts[child];
                        if (total < cap) {
                            const to_copy = @min(c, cap - total);
                            @memcpy(out_ids[total .. total + to_copy], self.vals[child].v[0..to_copy]);
                        }
                        total += c;
                    } else {
                        @prefetch(&self.boxes[child], .{ .rw = .read, .locality = 1, .cache = .data });
                        stack[sp] = .{ .node = child, .level = 0 };
                        sp += 1;
                    }
                }
            } else {
                const child_lvl = frame.level - 1;
                while (mask != 0) {
                    const i: usize = @ctz(mask);
                    mask &= mask - 1;
                    const child: u32 = @bitCast(vals[i]);
                    if (qx0 <= b.x0[i] and b.x1[i] <= qx1 and qy0 <= b.y0[i] and b.y1[i] <= qy1) {
                        self.collectSubtree(child, child_lvl, out_ids, &total);
                    } else {
                        @prefetch(&self.boxes[child], .{ .rw = .read, .locality = 1, .cache = .data });
                        stack[sp] = .{ .node = child, .level = child_lvl };
                        sp += 1;
                    }
                }
            }
        }
        return total;
    }

    // --------------------------------------------------------- nearest (k-NN)

    inline fn computeDists(b: *const NodeBoxes, px_v: V16i32, py_v: V16i32) V16u64 {
        const zero_v: V16i32 = @splat(0);
        const dx: V16i32 = @max(@max(@as(V16i32, b.x0) - px_v, px_v - @as(V16i32, b.x1)), zero_v);
        const dy: V16i32 = @max(@max(@as(V16i32, b.y0) - py_v, py_v - @as(V16i32, b.y1)), zero_v);
        const dx64: V16i64 = dx;
        const dy64: V16i64 = dy;
        return @bitCast(dx64 * dx64 + dy64 * dy64);
    }

    fn growHeap(self: *RTree, min_cap: usize) Allocator.Error!void {
        @branchHint(.cold);
        var new_cap: usize = if (self.nn_heap.len == 0) 256 else self.nn_heap.len * 2;
        while (new_cap < min_cap) new_cap *= 2;
        if (self.nn_heap.len == 0) {
            self.nn_heap = try self.allocator.alloc(HeapItem, new_cap);
        } else {
            self.nn_heap = try self.allocator.realloc(self.nn_heap, new_cap);
        }
    }

    inline fn heapPush(self: *RTree, heap_len: *usize, item: HeapItem) Allocator.Error!void {
        var idx = heap_len.*;
        if (idx == self.nn_heap.len) {
            try self.growHeap(idx + 1);
        }
        const h = self.nn_heap;
        while (idx > 0) {
            const parent = (idx - 1) >> 2;
            if (h[parent].dist <= item.dist) break;
            h[idx] = h[parent];
            idx = parent;
        }
        h[idx] = item;
        heap_len.* += 1;
    }

    inline fn heapPop(h: []HeapItem, heap_len: *usize) HeapItem {
        const top = h[0];
        const new_len = heap_len.* - 1;
        heap_len.* = new_len;
        if (new_len == 0) return top;

        const last = h[new_len];
        var idx: usize = 0;
        while (true) {
            const first_child = (idx << 2) + 1;
            if (first_child >= new_len) break;
            var best_c = first_child;
            var best_d = h[first_child].dist;
            const end_c = @min(first_child + 4, new_len);
            var c = first_child + 1;
            while (c < end_c) : (c += 1) {
                if (h[c].dist < best_d) {
                    best_d = h[c].dist;
                    best_c = c;
                }
            }
            if (last.dist <= best_d) break;
            h[idx] = h[best_c];
            idx = best_c;
        }
        h[idx] = last;
        return top;
    }

    inline fn kHeapPush(buf: []KItem, len_ptr: *usize, item: KItem) void {
        var idx = len_ptr.*;
        while (idx > 0) {
            const parent = (idx - 1) >> 1;
            if (!item.isWorse(buf[parent])) break;
            buf[idx] = buf[parent];
            idx = parent;
        }
        buf[idx] = item;
        len_ptr.* += 1;
    }

    inline fn kHeapReplaceTop(buf: []KItem, n: usize, item: KItem) void {
        var idx: usize = 0;
        while (true) {
            const left = (idx << 1) + 1;
            if (left >= n) break;
            var worst = left;
            const right = left + 1;
            if (right < n and buf[right].isWorse(buf[left])) {
                worst = right;
            }
            if (!buf[worst].isWorse(item)) break;
            buf[idx] = buf[worst];
            idx = worst;
        }
        buf[idx] = item;
    }

    pub fn nearest(self: *RTree, px: i32, py: i32, k: usize, out_ids: []i32) Allocator.Error!usize {
        if (k == 0 or self.entry_count == 0) return 0;
        const target_k = @min(k, self.entry_count);

        if (target_k == 1) {
            return self.nearestOne(px, py, out_ids);
        } else if (target_k <= 16) {
            return self.nearestSmallK(px, py, target_k, out_ids);
        } else {
            return self.nearestLargeK(px, py, target_k, out_ids);
        }
    }

    fn nearestOne(self: *RTree, px: i32, py: i32, out_ids: []i32) Allocator.Error!usize {
        const px_v: V16i32 = @splat(px);
        const py_v: V16i32 = @splat(py);

        var best_dist: u64 = SENTINEL_CUTOFF;
        var best_id: i32 = std.math.maxInt(i32);

        // Phase 1: Best-first-exact greedy descent to first leaf, deferring siblings
        // so most siblings are pruned by the first leaf's cutoff before touching the heap.
        var deferred: [MAX_DEPTH * MAX_ENTRIES]HeapItem = undefined;
        var def_len: usize = 0;
        var min_def_dist: u64 = std.math.maxInt(u64);

        var cur_node: u32 = self.root;
        var cur_lvl: u8 = self.tree_height - 1;
        var heap_len: usize = 0;

        while (cur_lvl > 0) {
            const b = &self.boxes[cur_node];
            const dists_v = computeDists(b, px_v, py_v);
            const min_d: u64 = @reduce(.Min, dists_v);
            const min_mask: u16 = @bitCast(dists_v == @as(V16u64, @splat(min_d)));
            const best_i: usize = @ctz(min_mask);

            const vals = &self.vals[cur_node].v;
            const child_lvl = cur_lvl - 1;
            const dists: [MAX_ENTRIES]u64 = dists_v;

            var valid_mask: u16 = @bitCast(dists_v < @as(V16u64, @splat(SENTINEL_CUTOFF)));
            valid_mask &= ~(@as(u16, 1) << @intCast(best_i));
            while (valid_mask != 0) {
                const i: usize = @ctz(valid_mask);
                valid_mask &= valid_mask - 1;
                const d = dists[i];
                if (d < min_def_dist) min_def_dist = d;
                deferred[def_len] = .{ .dist = d, .node = @bitCast(vals[i]), .level = child_lvl };
                def_len += 1;
            }

            if (min_d <= min_def_dist) {
                cur_node = @bitCast(vals[best_i]);
                cur_lvl = child_lvl;
            } else {
                deferred[def_len] = .{ .dist = min_d, .node = @bitCast(vals[best_i]), .level = child_lvl };
                def_len += 1;
                break;
            }
        }

        // If we reached a leaf directly, evaluate it now to establish a tight cutoff.
        if (cur_lvl == 0) {
            const dists_v = computeDists(&self.boxes[cur_node], px_v, py_v);
            const min_d: u64 = @reduce(.Min, dists_v);
            if (min_d <= best_dist) {
                var tie_mask: u16 = @bitCast(dists_v == @as(V16u64, @splat(min_d)));
                const vals = &self.vals[cur_node].v;
                while (tie_mask != 0) {
                    const i: usize = @ctz(tie_mask);
                    tie_mask &= tie_mask - 1;
                    const id = vals[i];
                    if (min_d < best_dist or id < best_id) {
                        best_dist = min_d;
                        best_id = id;
                    }
                }
            }
        }

        // Flush surviving deferred items into the 4-ary min-heap.
        for (deferred[0..def_len]) |item| {
            if (item.dist <= best_dist) {
                try self.heapPush(&heap_len, item);
            }
        }

        // Phase 2: Bounded best-first search.
        while (heap_len > 0) {
            if (self.nn_heap[0].dist > best_dist) break;
            var cur = heapPop(self.nn_heap, &heap_len);

            while (true) {
                if (cur.level == 0) {
                    const dists_v = computeDists(&self.boxes[cur.node], px_v, py_v);
                    const min_d: u64 = @reduce(.Min, dists_v);
                    if (min_d <= best_dist) {
                        var tie_mask: u16 = @bitCast(dists_v == @as(V16u64, @splat(min_d)));
                        const vals = &self.vals[cur.node].v;
                        while (tie_mask != 0) {
                            const i: usize = @ctz(tie_mask);
                            tie_mask &= tie_mask - 1;
                            const id = vals[i];
                            if (min_d < best_dist or id < best_id) {
                                best_dist = min_d;
                                best_id = id;
                            }
                        }
                    }
                    break;
                }

                const dists_v = computeDists(&self.boxes[cur.node], px_v, py_v);
                var mask: u16 = @bitCast(dists_v <= @as(V16u64, @splat(best_dist)));
                if (mask == 0) break;

                const vals = &self.vals[cur.node].v;
                const child_lvl = cur.level - 1;
                const dists: [MAX_ENTRIES]u64 = dists_v;

                // Pick minimum-distance child to potentially descend directly.
                var best_i: usize = @ctz(mask);
                var best_c_d: u64 = dists[best_i];
                var scan = mask & (mask - 1);
                while (scan != 0) {
                    const i: usize = @ctz(scan);
                    scan &= scan - 1;
                    if (dists[i] < best_c_d) {
                        best_c_d = dists[i];
                        best_i = i;
                    }
                }

                const next_node: u32 = @bitCast(vals[best_i]);
                @prefetch(&self.boxes[next_node], .{ .rw = .read, .locality = 1, .cache = .data });

                mask &= ~(@as(u16, 1) << @intCast(best_i));
                while (mask != 0) {
                    const i: usize = @ctz(mask);
                    mask &= mask - 1;
                    try self.heapPush(&heap_len, .{
                        .dist = dists[i],
                        .node = @bitCast(vals[i]),
                        .level = child_lvl,
                    });
                }

                const next_item = HeapItem{
                    .dist = best_c_d,
                    .node = next_node,
                    .level = child_lvl,
                };
                if (heap_len == 0 or best_c_d <= self.nn_heap[0].dist) {
                    cur = next_item;
                } else {
                    try self.heapPush(&heap_len, next_item);
                    break;
                }
            }
        }

        out_ids[0] = best_id;
        return 1;
    }

    inline fn insertSmallK(
        res: *[16]KItem,
        res_len: *usize,
        target_k: usize,
        cutoff_dist: *u64,
        cutoff_id: *i32,
        d: u64,
        id: i32,
    ) void {
        const cur_len = res_len.*;
        if (cur_len == target_k) {
            if (d > cutoff_dist.* or (d == cutoff_dist.* and id >= cutoff_id.*)) return;
        }
        const item = KItem{ .dist = d, .id = id };
        var pos: usize = if (cur_len < target_k) cur_len else target_k - 1;
        while (pos > 0 and item.isBetter(res[pos - 1])) {
            res[pos] = res[pos - 1];
            pos -= 1;
        }
        res[pos] = item;
        if (cur_len < target_k) {
            res_len.* = cur_len + 1;
            if (cur_len + 1 == target_k) {
                cutoff_dist.* = res[target_k - 1].dist;
                cutoff_id.* = res[target_k - 1].id;
            }
        } else {
            cutoff_dist.* = res[target_k - 1].dist;
            cutoff_id.* = res[target_k - 1].id;
        }
    }

    fn nearestSmallK(self: *RTree, px: i32, py: i32, target_k: usize, out_ids: []i32) Allocator.Error!usize {
        const px_v: V16i32 = @splat(px);
        const py_v: V16i32 = @splat(py);

        var res: [16]KItem = undefined;
        var res_len: usize = 0;
        var cutoff_dist: u64 = SENTINEL_CUTOFF;
        var cutoff_id: i32 = std.math.maxInt(i32);

        var deferred: [MAX_DEPTH * MAX_ENTRIES]HeapItem = undefined;
        var def_len: usize = 0;
        var min_def_dist: u64 = std.math.maxInt(u64);

        var cur_node: u32 = self.root;
        var cur_lvl: u8 = self.tree_height - 1;
        var heap_len: usize = 0;

        while (cur_lvl > 0) {
            const b = &self.boxes[cur_node];
            const dists_v = computeDists(b, px_v, py_v);
            const min_d: u64 = @reduce(.Min, dists_v);
            const min_mask: u16 = @bitCast(dists_v == @as(V16u64, @splat(min_d)));
            const best_i: usize = @ctz(min_mask);

            const vals = &self.vals[cur_node].v;
            const child_lvl = cur_lvl - 1;
            const dists: [MAX_ENTRIES]u64 = dists_v;

            var valid_mask: u16 = @bitCast(dists_v < @as(V16u64, @splat(SENTINEL_CUTOFF)));
            valid_mask &= ~(@as(u16, 1) << @intCast(best_i));
            while (valid_mask != 0) {
                const i: usize = @ctz(valid_mask);
                valid_mask &= valid_mask - 1;
                const d = dists[i];
                if (d < min_def_dist) min_def_dist = d;
                deferred[def_len] = .{ .dist = d, .node = @bitCast(vals[i]), .level = child_lvl };
                def_len += 1;
            }

            if (min_d <= min_def_dist) {
                cur_node = @bitCast(vals[best_i]);
                cur_lvl = child_lvl;
            } else {
                deferred[def_len] = .{ .dist = min_d, .node = @bitCast(vals[best_i]), .level = child_lvl };
                def_len += 1;
                break;
            }
        }

        if (cur_lvl == 0) {
            const dists_v = computeDists(&self.boxes[cur_node], px_v, py_v);
            var hit_mask: u16 = @bitCast(dists_v <= @as(V16u64, @splat(cutoff_dist)));
            if (hit_mask != 0) {
                const dists: [MAX_ENTRIES]u64 = dists_v;
                const vals = &self.vals[cur_node].v;
                while (hit_mask != 0) {
                    const i: usize = @ctz(hit_mask);
                    hit_mask &= hit_mask - 1;
                    insertSmallK(&res, &res_len, target_k, &cutoff_dist, &cutoff_id, dists[i], vals[i]);
                }
            }
        }

        for (deferred[0..def_len]) |item| {
            if (item.dist <= cutoff_dist) {
                try self.heapPush(&heap_len, item);
            }
        }

        while (heap_len > 0) {
            if (self.nn_heap[0].dist > cutoff_dist) break;
            var cur = heapPop(self.nn_heap, &heap_len);

            while (true) {
                if (cur.level == 0) {
                    const dists_v = computeDists(&self.boxes[cur.node], px_v, py_v);
                    var hit_mask: u16 = @bitCast(dists_v <= @as(V16u64, @splat(cutoff_dist)));
                    if (hit_mask != 0) {
                        const dists: [MAX_ENTRIES]u64 = dists_v;
                        const vals = &self.vals[cur.node].v;
                        while (hit_mask != 0) {
                            const i: usize = @ctz(hit_mask);
                            hit_mask &= hit_mask - 1;
                            insertSmallK(&res, &res_len, target_k, &cutoff_dist, &cutoff_id, dists[i], vals[i]);
                        }
                    }
                    break;
                }

                const dists_v = computeDists(&self.boxes[cur.node], px_v, py_v);
                var mask: u16 = @bitCast(dists_v <= @as(V16u64, @splat(cutoff_dist)));
                if (mask == 0) break;

                const vals = &self.vals[cur.node].v;
                const child_lvl = cur.level - 1;
                const dists: [MAX_ENTRIES]u64 = dists_v;

                var best_i: usize = @ctz(mask);
                var best_c_d: u64 = dists[best_i];
                var scan = mask & (mask - 1);
                while (scan != 0) {
                    const i: usize = @ctz(scan);
                    scan &= scan - 1;
                    if (dists[i] < best_c_d) {
                        best_c_d = dists[i];
                        best_i = i;
                    }
                }

                const next_node: u32 = @bitCast(vals[best_i]);
                @prefetch(&self.boxes[next_node], .{ .rw = .read, .locality = 1, .cache = .data });

                mask &= ~(@as(u16, 1) << @intCast(best_i));
                while (mask != 0) {
                    const i: usize = @ctz(mask);
                    mask &= mask - 1;
                    try self.heapPush(&heap_len, .{
                        .dist = dists[i],
                        .node = @bitCast(vals[i]),
                        .level = child_lvl,
                    });
                }

                const next_item = HeapItem{
                    .dist = best_c_d,
                    .node = next_node,
                    .level = child_lvl,
                };
                if (heap_len == 0 or best_c_d <= self.nn_heap[0].dist) {
                    cur = next_item;
                } else {
                    try self.heapPush(&heap_len, next_item);
                    break;
                }
            }
        }

        for (0..res_len) |i| {
            out_ids[i] = res[i].id;
        }
        return res_len;
    }

    fn nearestLargeK(self: *RTree, px: i32, py: i32, target_k: usize, out_ids: []i32) Allocator.Error!usize {
        if (self.nn_kbuf.len < target_k) {
            if (self.nn_kbuf.len == 0) {
                self.nn_kbuf = try self.allocator.alloc(KItem, target_k);
            } else {
                self.nn_kbuf = try self.allocator.realloc(self.nn_kbuf, target_k);
            }
        }
        const kbuf = self.nn_kbuf;
        var klen: usize = 0;
        var cutoff_dist: u64 = SENTINEL_CUTOFF;

        const px_v: V16i32 = @splat(px);
        const py_v: V16i32 = @splat(py);

        var heap_len: usize = 0;
        try self.heapPush(&heap_len, .{ .dist = 0, .node = self.root, .level = self.tree_height - 1 });

        while (heap_len > 0) {
            if (self.nn_heap[0].dist > cutoff_dist) break;
            const cur = heapPop(self.nn_heap, &heap_len);

            const dists_v = computeDists(&self.boxes[cur.node], px_v, py_v);
            var mask: u16 = @bitCast(dists_v <= @as(V16u64, @splat(cutoff_dist)));
            if (mask == 0) continue;

            const dists: [MAX_ENTRIES]u64 = dists_v;
            const vals = &self.vals[cur.node].v;

            if (cur.level == 0) {
                while (mask != 0) {
                    const i: usize = @ctz(mask);
                    mask &= mask - 1;
                    const item = KItem{ .dist = dists[i], .id = vals[i] };
                    if (klen < target_k) {
                        kHeapPush(kbuf, &klen, item);
                        if (klen == target_k) {
                            cutoff_dist = kbuf[0].dist;
                        }
                    } else if (item.isBetter(kbuf[0])) {
                        kHeapReplaceTop(kbuf, target_k, item);
                        cutoff_dist = kbuf[0].dist;
                    }
                }
            } else {
                const child_lvl = cur.level - 1;
                while (mask != 0) {
                    const i: usize = @ctz(mask);
                    mask &= mask - 1;
                    try self.heapPush(&heap_len, .{
                        .dist = dists[i],
                        .node = @bitCast(vals[i]),
                        .level = child_lvl,
                    });
                }
            }
        }

        std.mem.sort(KItem, kbuf[0..klen], {}, struct {
            fn lessThan(_: void, a: KItem, b: KItem) bool {
                return a.isBetter(b);
            }
        }.lessThan);

        for (0..klen) |i| {
            out_ids[i] = kbuf[i].id;
        }
        return klen;
    }
};
