#pragma once

#include <algorithm>
#include <bit>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <new>
#include <type_traits>
#include <vector>

class RTree {
public:
    RTree() = default;
    ~RTree() = default;

    RTree(const RTree&) = delete;
    RTree& operator=(const RTree&) = delete;

    void insert(std::int32_t x0, std::int32_t y0, std::int32_t x1, std::int32_t y1,
                std::int32_t id) {
        if (height_ == 0) [[unlikely]] {
            uint32_t leaf = leaf_nodes_.alloc();
            init_node_single(leaf_nodes_[leaf], x0, y0, x1, y1, id);
            root_ = leaf;
            height_ = 1;
            len_ = 1;
            return;
        }
        ++len_;
        insert_at_level(x0, y0, x1, y1, id, 0);
    }

    bool remove(std::int32_t x0, std::int32_t y0, std::int32_t x1, std::int32_t y1,
                std::int32_t id) {
        if (height_ == 0) [[unlikely]] return false;

        if (height_ == 1) [[unlikely]] {
            Node& leaf = leaf_nodes_[root_];
            int32_t slot = find_entry_in_leaf(leaf, x0, y0, x1, y1, id);
            if (slot < 0) return false;
            remove_slot(leaf, static_cast<uint32_t>(slot));
            --len_;
            if (leaf.count == 0) {
                leaf_nodes_.reset();
                internal_nodes_.reset();
                root_ = INVALID_NODE;
                height_ = 0;
            }
            return true;
        }

        const uint32_t h = height_;
        uint32_t stack_node[MAX_HEIGHT];
        uint32_t stack_mask[MAX_HEIGHT];
        uint8_t path_slot[MAX_HEIGHT];

        const i32x4 vx0_q = {x0, x0, x0, x0};
        const i32x4 vx1_q = {x1, x1, x1, x1};
        const i32x4 vy0_q = {y0, y0, y0, y0};
        const i32x4 vy1_q = {y1, y1, y1, y1};

        stack_node[0] = root_;
        uint32_t root_mask = mask_contains(internal_nodes_[root_], vx0_q, vx1_q, vy0_q, vy1_q);
        if (root_mask == 0) return false;
        stack_mask[0] = root_mask;

        int d = 0;
        uint32_t found_leaf = INVALID_NODE;
        int32_t found_slot = -1;

        while (d >= 0) {
            uint32_t m = stack_mask[d];
            if (m == 0) {
                --d;
                continue;
            }
            uint32_t s = static_cast<uint32_t>(__builtin_ctz(m));
            uint32_t rem = m & (m - 1);
            stack_mask[d] = rem;
            path_slot[d + 1] = static_cast<uint8_t>(s);

            const Node& cur = internal_nodes_[stack_node[d]];
            uint32_t child = static_cast<uint32_t>(cur.val[s]);

            if (static_cast<uint32_t>(d) + 2 == h) {
                if (rem) {
                    uint32_t next_s = static_cast<uint32_t>(__builtin_ctz(rem));
                    __builtin_prefetch(leaf_nodes_.ptr(static_cast<uint32_t>(cur.val[next_s])), 0, 3);
                }
                int32_t slot = find_entry_in_leaf_vec(leaf_nodes_[child], vx0_q, vx1_q, vy0_q, vy1_q, id);
                if (slot >= 0) {
                    stack_node[d + 1] = child;
                    found_leaf = child;
                    found_slot = slot;
                    break;
                }
            } else {
                uint32_t cm = mask_contains(internal_nodes_[child], vx0_q, vx1_q, vy0_q, vy1_q);
                if (cm != 0) {
                    ++d;
                    stack_node[d] = child;
                    stack_mask[d] = cm;
                }
            }
        }

        if (found_slot < 0) return false;

        --len_;
        Node& leaf = leaf_nodes_[found_leaf];
        remove_slot(leaf, static_cast<uint32_t>(found_slot));

        if (leaf.count >= MIN_ENTRIES) [[likely]] {
            Node& parent = internal_nodes_[stack_node[h - 2]];
            uint32_t ps = path_slot[h - 1];
            if (x0 > parent.x0[ps] && x1 < parent.x1[ps] &&
                y0 > parent.y0[ps] && y1 < parent.y1[ps]) [[likely]] {
                return true;
            }
            Rect nb = compute_bbox(leaf);
            if (nb.x0 == parent.x0[ps] && nb.x1 == parent.x1[ps] &&
                nb.y0 == parent.y0[ps] && nb.y1 == parent.y1[ps]) {
                return true;
            }
            propagate_shrink(stack_node, path_slot, h - 2, ps, nb);
            return true;
        }

        condense_and_reinsert(stack_node, path_slot, h);
        return true;
    }

    std::size_t search(std::int32_t qx0, std::int32_t qy0, std::int32_t qx1, std::int32_t qy1,
                       std::int32_t* out_ids, std::size_t cap) const {
        if (height_ == 0) [[unlikely]] return 0;
        if (qx0 == qx1 && qy0 == qy1) {
            return search_impl<false>(qx0, qy0, qx1, qy1, out_ids, cap);
        }
        return search_impl<true>(qx0, qy0, qx1, qy1, out_ids, cap);
    }

    std::size_t nearest(std::int32_t px, std::int32_t py, std::size_t k,
                        std::int32_t* out_ids) const {
        if (k == 0 || len_ == 0) [[unlikely]] return 0;
        if (k == 1) {
            return nearest_one(px, py, out_ids);
        }
        return nearest_k(px, py, std::min(k, len_), out_ids);
    }

    std::size_t len() const { return len_; }
    std::size_t height() const { return height_; }
    std::size_t node_count() const {
        return leaf_nodes_.active_count() + internal_nodes_.active_count();
    }

private:
    using i32x2 = std::int32_t __attribute__((ext_vector_type(2)));
    using i32x4 = std::int32_t __attribute__((ext_vector_type(4)));
    using u32x4 = std::uint32_t __attribute__((ext_vector_type(4)));
    using i64x2 = std::int64_t __attribute__((ext_vector_type(2)));

    static constexpr int32_t SENTINEL_MAX = 1 << 24;
    static constexpr int32_t SENTINEL_MIN = -(1 << 24);
    static constexpr uint32_t MAX_ENTRIES = 16;
    static constexpr uint32_t MIN_ENTRIES = 6;
    static constexpr uint32_t INVALID_NODE = UINT32_MAX;
    static constexpr uint32_t MAX_HEIGHT = 24;
    static constexpr uint32_t LEVEL_BITS = 5;
    static constexpr uint32_t LEVEL_MASK = (1u << LEVEL_BITS) - 1u;
    static constexpr uint64_t INF_DIST = 1ULL << 42;
    static constexpr int32_t INF_RADIUS = 1 << 21;

    struct Rect {
        int32_t x0, y0, x1, y1;
    };

    struct alignas(128) Node {
        int32_t x0[16];   // CL 0: 0..63
        int32_t x1[16];   // CL 0: 64..127
        int32_t y0[16];   // CL 1: 128..191
        int32_t y1[16];   // CL 1: 192..255
        int32_t val[16];  // CL 2: 256..319
        uint32_t count;   // CL 2: 320..323
    };
    static_assert(sizeof(Node) == 384);
    static_assert(alignof(Node) == 128);
    static_assert(std::is_trivially_copyable_v<Node>);

    template <typename T>
    class AlignedPool {
        T* data_ = nullptr;
        uint32_t size_ = 0;
        uint32_t cap_ = 0;
        std::vector<uint32_t> free_list_;

    public:
        AlignedPool() = default;
        ~AlignedPool() {
            if (data_) ::operator delete(data_, std::align_val_t{alignof(T)});
        }
        AlignedPool(const AlignedPool&) = delete;
        AlignedPool& operator=(const AlignedPool&) = delete;

        uint32_t alloc() {
            if (!free_list_.empty()) {
                uint32_t idx = free_list_.back();
                free_list_.pop_back();
                return idx;
            }
            if (size_ == cap_) [[unlikely]] {
                grow();
            }
            return size_++;
        }

        void free(uint32_t idx) { free_list_.push_back(idx); }

        void reset() {
            size_ = 0;
            free_list_.clear();
        }

        T& operator[](uint32_t idx) { return data_[idx]; }
        const T& operator[](uint32_t idx) const { return data_[idx]; }
        T* ptr(uint32_t idx) { return data_ + idx; }
        const T* ptr(uint32_t idx) const { return data_ + idx; }
        std::size_t active_count() const {
            return static_cast<std::size_t>(size_) - free_list_.size();
        }

    private:
        __attribute__((noinline)) void grow() {
            uint32_t new_cap = cap_ == 0 ? 16u : cap_ * 2u;
            T* new_data = static_cast<T*>(
                ::operator new(static_cast<std::size_t>(new_cap) * sizeof(T),
                               std::align_val_t{alignof(T)}));
            if (data_) {
                std::memcpy(new_data, data_, static_cast<std::size_t>(size_) * sizeof(T));
                ::operator delete(data_, std::align_val_t{alignof(T)});
            }
            data_ = new_data;
            cap_ = new_cap;
        }
    };

    struct Cand {
        uint64_t key;  // (dist << LEVEL_BITS) | level
        uint32_t node;
    };

    struct ResItem {
        uint64_t dist;
        int32_t id;
    };

    AlignedPool<Node> leaf_nodes_;
    AlignedPool<Node> internal_nodes_;
    uint32_t root_ = INVALID_NODE;
    uint32_t height_ = 0;
    std::size_t len_ = 0;

    mutable std::vector<Cand> heap_;
    mutable std::vector<ResItem> res_vec_;

    // --------------------------------------------------------- vector helpers

    static inline i32x4 load4(const int32_t* p) {
        i32x4 v;
        std::memcpy(&v, __builtin_assume_aligned(p, 16), 16);
        return v;
    }

    static inline i32x4 load4u(const int32_t* p) {
        i32x4 v;
        std::memcpy(&v, p, 16);
        return v;
    }

    static inline i64x2 load2u(const int64_t* p) {
        i64x2 v;
        std::memcpy(&v, p, 16);
        return v;
    }

    static inline void store4(int32_t* p, i32x4 v) {
        std::memcpy(__builtin_assume_aligned(p, 16), &v, 16);
    }

    static inline i32x4 vmin4(i32x4 a, i32x4 b) { return a < b ? a : b; }
    static inline i32x4 vmax4(i32x4 a, i32x4 b) { return a > b ? a : b; }

    static inline i64x2 mul_lo(i32x4 a, i32x4 b) {
        return __builtin_convertvector(a.lo, i64x2) * __builtin_convertvector(b.lo, i64x2);
    }

    static inline i64x2 mul_hi(i32x4 a, i32x4 b) {
        return __builtin_convertvector(a.hi, i64x2) * __builtin_convertvector(b.hi, i64x2);
    }

    static inline bool any_nonzero16(i32x4 m0, i32x4 m1, i32x4 m2, i32x4 m3) {
        u32x4 u = std::bit_cast<u32x4>((m0 | m1) | (m2 | m3));
        return (u[0] | u[1] | u[2] | u[3]) != 0;
    }

    static inline uint32_t pack_mask16(i32x4 m0, i32x4 m1, i32x4 m2, i32x4 m3) {
        constexpr u32x4 B0 = {1u << 0, 1u << 1, 1u << 2, 1u << 3};
        constexpr u32x4 B1 = {1u << 4, 1u << 5, 1u << 6, 1u << 7};
        constexpr u32x4 B2 = {1u << 8, 1u << 9, 1u << 10, 1u << 11};
        constexpr u32x4 B3 = {1u << 12, 1u << 13, 1u << 14, 1u << 15};
        u32x4 acc = (std::bit_cast<u32x4>(m0) & B0) |
                    (std::bit_cast<u32x4>(m1) & B1) |
                    (std::bit_cast<u32x4>(m2) & B2) |
                    (std::bit_cast<u32x4>(m3) & B3);
        return acc[0] + acc[1] + acc[2] + acc[3];
    }

    static inline int32_t isqrt_floor(uint64_t v) {
        int32_t r = static_cast<int32_t>(std::sqrt(static_cast<double>(v)));
        if (static_cast<uint64_t>(r) * static_cast<uint64_t>(r) > v) --r;
        return r;
    }

    static inline void init_node_single(Node& n, int32_t x0, int32_t y0, int32_t x1, int32_t y1,
                                        int32_t val) {
        const i32x4 smax = {SENTINEL_MAX, SENTINEL_MAX, SENTINEL_MAX, SENTINEL_MAX};
        const i32x4 smin = {SENTINEL_MIN, SENTINEL_MIN, SENTINEL_MIN, SENTINEL_MIN};
        for (int k = 0; k < 4; ++k) {
            store4(n.x0 + 4 * k, smax);
            store4(n.x1 + 4 * k, smin);
            store4(n.y0 + 4 * k, smax);
            store4(n.y1 + 4 * k, smin);
        }
        n.x0[0] = x0;
        n.x1[0] = x1;
        n.y0[0] = y0;
        n.y1[0] = y1;
        n.val[0] = val;
        n.count = 1;
    }

    static inline void init_node_pair(Node& n, const Rect& b1, int32_t v1,
                                      const Rect& b2, int32_t v2) {
        const i32x4 smax = {SENTINEL_MAX, SENTINEL_MAX, SENTINEL_MAX, SENTINEL_MAX};
        const i32x4 smin = {SENTINEL_MIN, SENTINEL_MIN, SENTINEL_MIN, SENTINEL_MIN};
        for (int k = 0; k < 4; ++k) {
            store4(n.x0 + 4 * k, smax);
            store4(n.x1 + 4 * k, smin);
            store4(n.y0 + 4 * k, smax);
            store4(n.y1 + 4 * k, smin);
        }
        n.x0[0] = b1.x0; n.x1[0] = b1.x1; n.y0[0] = b1.y0; n.y1[0] = b1.y1; n.val[0] = v1;
        n.x0[1] = b2.x0; n.x1[1] = b2.x1; n.y0[1] = b2.y0; n.y1[1] = b2.y1; n.val[1] = v2;
        n.count = 2;
    }

    static inline void remove_slot(Node& n, uint32_t slot) {
        uint32_t last = --n.count;
        if (slot != last) {
            n.x0[slot] = n.x0[last];
            n.x1[slot] = n.x1[last];
            n.y0[slot] = n.y0[last];
            n.y1[slot] = n.y1[last];
            n.val[slot] = n.val[last];
        }
        n.x0[last] = SENTINEL_MAX;
        n.x1[last] = SENTINEL_MIN;
        n.y0[last] = SENTINEL_MAX;
        n.y1[last] = SENTINEL_MIN;
    }

    static inline Rect compute_bbox(const Node& n) {
        i32x4 vx0 = vmin4(vmin4(load4(n.x0 + 0), load4(n.x0 + 4)),
                          vmin4(load4(n.x0 + 8), load4(n.x0 + 12)));
        i32x4 vx1 = vmax4(vmax4(load4(n.x1 + 0), load4(n.x1 + 4)),
                          vmax4(load4(n.x1 + 8), load4(n.x1 + 12)));
        i32x4 vy0 = vmin4(vmin4(load4(n.y0 + 0), load4(n.y0 + 4)),
                          vmin4(load4(n.y0 + 8), load4(n.y0 + 12)));
        i32x4 vy1 = vmax4(vmax4(load4(n.y1 + 0), load4(n.y1 + 4)),
                          vmax4(load4(n.y1 + 8), load4(n.y1 + 12)));
        int32_t bx0 = std::min(std::min(vx0[0], vx0[1]), std::min(vx0[2], vx0[3]));
        int32_t bx1 = std::max(std::max(vx1[0], vx1[1]), std::max(vx1[2], vx1[3]));
        int32_t by0 = std::min(std::min(vy0[0], vy0[1]), std::min(vy0[2], vy0[3]));
        int32_t by1 = std::max(std::max(vy1[0], vy1[1]), std::max(vy1[2], vy1[3]));
        return {bx0, by0, bx1, by1};
    }

    // --------------------------------------------------------- masks

    static inline uint32_t mask_intersects(const Node& n, i32x4 vqx0, i32x4 vqx1,
                                           i32x4 vqy0, i32x4 vqy1) {
        i32x4 mx0 = (load4(n.x0 + 0) <= vqx1) & (vqx0 <= load4(n.x1 + 0));
        i32x4 mx1 = (load4(n.x0 + 4) <= vqx1) & (vqx0 <= load4(n.x1 + 4));
        i32x4 mx2 = (load4(n.x0 + 8) <= vqx1) & (vqx0 <= load4(n.x1 + 8));
        i32x4 mx3 = (load4(n.x0 + 12) <= vqx1) & (vqx0 <= load4(n.x1 + 12));
        if (!any_nonzero16(mx0, mx1, mx2, mx3)) return 0;

        i32x4 m0 = mx0 & (load4(n.y0 + 0) <= vqy1) & (vqy0 <= load4(n.y1 + 0));
        i32x4 m1 = mx1 & (load4(n.y0 + 4) <= vqy1) & (vqy0 <= load4(n.y1 + 4));
        i32x4 m2 = mx2 & (load4(n.y0 + 8) <= vqy1) & (vqy0 <= load4(n.y1 + 8));
        i32x4 m3 = mx3 & (load4(n.y0 + 12) <= vqy1) & (vqy0 <= load4(n.y1 + 12));
        return pack_mask16(m0, m1, m2, m3);
    }

    static inline uint32_t mask_contains(const Node& n, i32x4 vx0, i32x4 vx1,
                                         i32x4 vy0, i32x4 vy1) {
        i32x4 mx0 = (load4(n.x0 + 0) <= vx0) & (vx1 <= load4(n.x1 + 0));
        i32x4 mx1 = (load4(n.x0 + 4) <= vx0) & (vx1 <= load4(n.x1 + 4));
        i32x4 mx2 = (load4(n.x0 + 8) <= vx0) & (vx1 <= load4(n.x1 + 8));
        i32x4 mx3 = (load4(n.x0 + 12) <= vx0) & (vx1 <= load4(n.x1 + 12));
        if (!any_nonzero16(mx0, mx1, mx2, mx3)) return 0;

        i32x4 m0 = mx0 & (load4(n.y0 + 0) <= vy0) & (vy1 <= load4(n.y1 + 0));
        i32x4 m1 = mx1 & (load4(n.y0 + 4) <= vy0) & (vy1 <= load4(n.y1 + 4));
        i32x4 m2 = mx2 & (load4(n.y0 + 8) <= vy0) & (vy1 <= load4(n.y1 + 8));
        i32x4 m3 = mx3 & (load4(n.y0 + 12) <= vy0) & (vy1 <= load4(n.y1 + 12));
        return pack_mask16(m0, m1, m2, m3);
    }

    static inline int32_t find_entry_in_leaf_vec(const Node& n, i32x4 vx0, i32x4 vx1,
                                                 i32x4 vy0, i32x4 vy1, int32_t id) {
        i32x4 mx0 = (load4(n.x0 + 0) == vx0) & (load4(n.x1 + 0) == vx1);
        i32x4 mx1 = (load4(n.x0 + 4) == vx0) & (load4(n.x1 + 4) == vx1);
        i32x4 mx2 = (load4(n.x0 + 8) == vx0) & (load4(n.x1 + 8) == vx1);
        i32x4 mx3 = (load4(n.x0 + 12) == vx0) & (load4(n.x1 + 12) == vx1);
        if (!any_nonzero16(mx0, mx1, mx2, mx3)) return -1;

        i32x4 m0 = mx0 & (load4(n.y0 + 0) == vy0) & (load4(n.y1 + 0) == vy1);
        i32x4 m1 = mx1 & (load4(n.y0 + 4) == vy0) & (load4(n.y1 + 4) == vy1);
        i32x4 m2 = mx2 & (load4(n.y0 + 8) == vy0) & (load4(n.y1 + 8) == vy1);
        i32x4 m3 = mx3 & (load4(n.y0 + 12) == vy0) & (load4(n.y1 + 12) == vy1);
        uint32_t mask = pack_mask16(m0, m1, m2, m3);
        while (mask) {
            uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
            mask &= mask - 1;
            if (n.val[i] == id) return static_cast<int32_t>(i);
        }
        return -1;
    }

    static inline int32_t find_entry_in_leaf(const Node& n, int32_t x0, int32_t y0,
                                             int32_t x1, int32_t y1, int32_t id) {
        i32x4 vx0 = {x0, x0, x0, x0}, vx1 = {x1, x1, x1, x1};
        i32x4 vy0 = {y0, y0, y0, y0}, vy1 = {y1, y1, y1, y1};
        return find_entry_in_leaf_vec(n, vx0, vx1, vy0, vy1, id);
    }

    // --------------------------------------------------------- search helpers

    template <bool CheckContainment>
    std::size_t search_impl(int32_t qx0, int32_t qy0, int32_t qx1, int32_t qy1,
                            int32_t* out_ids, std::size_t cap) const {
        const i32x4 vqx0 = {qx0, qx0, qx0, qx0};
        const i32x4 vqx1 = {qx1, qx1, qx1, qx1};
        const i32x4 vqy0 = {qy0, qy0, qy0, qy0};
        const i32x4 vqy1 = {qy1, qy1, qy1, qy1};

        std::size_t total = 0;

        if (height_ == 1) [[unlikely]] {
            scan_leaf_search(leaf_nodes_[root_], vqx0, vqx1, vqy0, vqy1, out_ids, cap, total);
            return total;
        }

        struct Frame {
            uint32_t node;
            uint32_t level;
        };
        Frame stack[384];
        int top = 0;
        stack[top++] = {root_, height_ - 1};

        while (top > 0) {
            Frame f = stack[--top];
            const Node& n = internal_nodes_[f.node];
            uint32_t mask = mask_intersects(n, vqx0, vqx1, vqy0, vqy1);
            if (mask == 0) continue;

            if (f.level == 1) {
                uint32_t part_leaves[16];
                int n_part = 0;
                if constexpr (CheckContainment) {
                    uint32_t full_leaves[16];
                    int n_full = 0;
                    while (mask) {
                        uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                        mask &= mask - 1;
                        uint32_t child = static_cast<uint32_t>(n.val[i]);
                        if (qx0 <= n.x0[i] && n.x1[i] <= qx1 && qy0 <= n.y0[i] && n.y1[i] <= qy1) {
                            full_leaves[n_full++] = child;
                            __builtin_prefetch(
                                reinterpret_cast<const char*>(leaf_nodes_.ptr(child)) + 256, 0, 3);
                        } else {
                            part_leaves[n_part++] = child;
                            __builtin_prefetch(leaf_nodes_.ptr(child), 0, 3);
                        }
                    }
                    for (int j = 0; j < n_full; ++j) {
                        collect_leaf(leaf_nodes_[full_leaves[j]], out_ids, cap, total);
                    }
                } else {
                    while (mask) {
                        uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                        mask &= mask - 1;
                        uint32_t child = static_cast<uint32_t>(n.val[i]);
                        part_leaves[n_part++] = child;
                        __builtin_prefetch(leaf_nodes_.ptr(child), 0, 3);
                    }
                }
                for (int j = 0; j < n_part; ++j) {
                    scan_leaf_search(leaf_nodes_[part_leaves[j]], vqx0, vqx1, vqy0, vqy1,
                                     out_ids, cap, total);
                }
            } else {
                uint32_t child_level = f.level - 1;
                if constexpr (CheckContainment) {
                    while (mask) {
                        uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                        mask &= mask - 1;
                        uint32_t child = static_cast<uint32_t>(n.val[i]);
                        if (qx0 <= n.x0[i] && n.x1[i] <= qx1 && qy0 <= n.y0[i] && n.y1[i] <= qy1) {
                            collect_subtree(child, child_level, out_ids, cap, total);
                        } else {
                            stack[top++] = {child, child_level};
                        }
                    }
                } else {
                    while (mask) {
                        uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                        mask &= mask - 1;
                        stack[top++] = {static_cast<uint32_t>(n.val[i]), child_level};
                    }
                }
            }
        }
        return total;
    }

    static inline void scan_leaf_search(const Node& leaf, i32x4 vqx0, i32x4 vqx1,
                                        i32x4 vqy0, i32x4 vqy1,
                                        std::int32_t* out_ids, std::size_t cap,
                                        std::size_t& total) {
        uint32_t mask = mask_intersects(leaf, vqx0, vqx1, vqy0, vqy1);
        if (mask == 0) return;

        if (total + MAX_ENTRIES <= cap) [[likely]] {
            std::size_t t = total;
            while (mask) {
                uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                mask &= mask - 1;
                out_ids[t++] = leaf.val[i];
            }
            total = t;
        } else if (total >= cap) {
            total += static_cast<std::size_t>(__builtin_popcount(mask));
        } else {
            std::size_t t = total;
            while (mask) {
                uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                mask &= mask - 1;
                if (t < cap) out_ids[t] = leaf.val[i];
                ++t;
            }
            total = t;
        }
    }

    static inline void collect_leaf(const Node& leaf, std::int32_t* out_ids, std::size_t cap,
                                    std::size_t& total) {
        uint32_t c = leaf.count;
        if (total + c <= cap) [[likely]] {
            std::memcpy(out_ids + total, leaf.val, static_cast<std::size_t>(c) * sizeof(int32_t));
        } else if (total < cap) {
            std::memcpy(out_ids + total, leaf.val, (cap - total) * sizeof(int32_t));
        }
        total += c;
    }

    __attribute__((noinline)) void collect_subtree(uint32_t root_node, uint32_t root_level,
                                                   std::int32_t* out_ids, std::size_t cap,
                                                   std::size_t& total) const {
        struct CFrame {
            uint32_t node;
            uint32_t level;
        };
        CFrame stack[384];
        int top = 0;
        stack[top++] = {root_node, root_level};

        while (top > 0) {
            CFrame f = stack[--top];
            if (f.level == 0) {
                collect_leaf(leaf_nodes_[f.node], out_ids, cap, total);
            } else if (f.level == 1) {
                const Node& n = internal_nodes_[f.node];
                uint32_t c = n.count;
                for (uint32_t i = 0; i < c; ++i) {
                    __builtin_prefetch(
                        reinterpret_cast<const char*>(leaf_nodes_.ptr(static_cast<uint32_t>(n.val[i]))) + 256,
                        0, 3);
                }
                for (uint32_t i = 0; i < c; ++i) {
                    collect_leaf(leaf_nodes_[static_cast<uint32_t>(n.val[i])], out_ids, cap, total);
                }
            } else {
                const Node& n = internal_nodes_[f.node];
                uint32_t c = n.count;
                uint32_t child_level = f.level - 1;
                for (uint32_t i = 0; i < c; ++i) {
                    stack[top++] = {static_cast<uint32_t>(n.val[i]), child_level};
                }
            }
        }
    }

    // --------------------------------------------------------- insert & split

    static inline uint32_t choose_subtree(const Node& n, int32_t rx0, int32_t ry0,
                                          int32_t rx1, int32_t ry1) {
        const uint32_t count = n.count;
        const i32x4 vrx0 = {rx0, rx0, rx0, rx0};
        const i32x4 vrx1 = {rx1, rx1, rx1, rx1};
        const i32x4 vry0 = {ry0, ry0, ry0, ry0};
        const i32x4 vry1 = {ry1, ry1, ry1, ry1};

        constexpr int64_t INF64 = std::numeric_limits<int64_t>::max();
        const i64x2 vinf = {INF64, INF64};
        const i64x2 vcnt = {static_cast<int64_t>(count), static_cast<int64_t>(count)};

        i64x2 best_e = vinf;
        i64x2 best_a = vinf;
        i64x2 best_i = {0, 0};

        for (uint32_t i = 0; i < count; i += 4) {
            i32x4 vx0 = load4(n.x0 + i);
            i32x4 vx1 = load4(n.x1 + i);
            i32x4 vy0 = load4(n.y0 + i);
            i32x4 vy1 = load4(n.y1 + i);

            i32x4 wx = vx1 - vx0;
            i32x4 wy = vy1 - vy0;
            i32x4 nwx = vmax4(vx1, vrx1) - vmin4(vx0, vrx0);
            i32x4 nwy = vmax4(vy1, vry1) - vmin4(vy0, vry0);

            i64x2 a_lo = mul_lo(wx, wy);
            i64x2 e_lo = mul_lo(nwx, nwy) - a_lo;
            i64x2 a_hi = mul_hi(wx, wy);
            i64x2 e_hi = mul_hi(nwx, nwy) - a_hi;

            i64x2 idx_lo = {static_cast<int64_t>(i), static_cast<int64_t>(i + 1)};
            i64x2 idx_hi = {static_cast<int64_t>(i + 2), static_cast<int64_t>(i + 3)};

            if (i + 4 > count) {
                e_lo = (idx_lo < vcnt) ? e_lo : vinf;
                e_hi = (idx_hi < vcnt) ? e_hi : vinf;
            }

            auto cmp_lo = (e_lo < best_e) | ((e_lo == best_e) & (a_lo < best_a));
            best_e = cmp_lo ? e_lo : best_e;
            best_a = cmp_lo ? a_lo : best_a;
            best_i = cmp_lo ? idx_lo : best_i;

            auto cmp_hi = (e_hi < best_e) | ((e_hi == best_e) & (a_hi < best_a));
            best_e = cmp_hi ? e_hi : best_e;
            best_a = cmp_hi ? a_hi : best_a;
            best_i = cmp_hi ? idx_hi : best_i;
        }

        if (best_e[1] < best_e[0] || (best_e[1] == best_e[0] && best_a[1] < best_a[0])) {
            return static_cast<uint32_t>(best_i[1]);
        }
        return static_cast<uint32_t>(best_i[0]);
    }

    __attribute__((noinline)) static void quadratic_split(
        Node& n1, Node& n2,
        int32_t add_x0, int32_t add_y0, int32_t add_x1, int32_t add_y1, int32_t add_val,
        Rect& b1_out, Rect& b2_out) {
        alignas(16) int32_t ex0[20], ex1[20], ey0[20], ey1[20], eval[20];
        std::memcpy(ex0, n1.x0, 16 * sizeof(int32_t));
        std::memcpy(ex1, n1.x1, 16 * sizeof(int32_t));
        std::memcpy(ey0, n1.y0, 16 * sizeof(int32_t));
        std::memcpy(ey1, n1.y1, 16 * sizeof(int32_t));
        std::memcpy(eval, n1.val, 16 * sizeof(int32_t));
        ex0[16] = add_x0;
        ex1[16] = add_x1;
        ey0[16] = add_y0;
        ey1[16] = add_y1;
        eval[16] = add_val;
        // Dummy padding entries [17..19] with huge area so they can never win PickSeeds.
        for (int k = 17; k < 20; ++k) {
            ex0[k] = 0; ex1[k] = 0; ey0[k] = 0; ey1[k] = 0;
        }

        alignas(16) int64_t areas[20];
        for (int i = 0; i < 17; ++i) {
            areas[i] = static_cast<int64_t>(ex1[i] - ex0[i]) * static_cast<int64_t>(ey1[i] - ey0[i]);
        }
        constexpr int64_t DUMMY_AREA = 1LL << 50;
        areas[17] = DUMMY_AREA;
        areas[18] = DUMMY_AREA;
        areas[19] = DUMMY_AREA;

        // 1. PickSeeds (vectorized 4-wide over j)
        constexpr int64_t MIN64 = std::numeric_limits<int64_t>::min();
        i64x2 best_d = {MIN64, MIN64};
        i64x2 best_pair = {0, 0};  // (i << 8) | j

        for (int i = 0; i < 16; ++i) {
            i32x4 vix0 = {ex0[i], ex0[i], ex0[i], ex0[i]};
            i32x4 vix1 = {ex1[i], ex1[i], ex1[i], ex1[i]};
            i32x4 viy0 = {ey0[i], ey0[i], ey0[i], ey0[i]};
            i32x4 viy1 = {ey1[i], ey1[i], ey1[i], ey1[i]};
            i64x2 via = {areas[i], areas[i]};
            int64_t base_i = static_cast<int64_t>(i) << 8;

            for (int j = i + 1; j < 17; j += 4) {
                i32x4 jx0 = load4u(ex0 + j);
                i32x4 jx1 = load4u(ex1 + j);
                i32x4 jy0 = load4u(ey0 + j);
                i32x4 jy1 = load4u(ey1 + j);

                i32x4 ux = vmax4(vix1, jx1) - vmin4(vix0, jx0);
                i32x4 uy = vmax4(viy1, jy1) - vmin4(viy0, jy0);

                i64x2 d_lo = mul_lo(ux, uy) - via - load2u(areas + j);
                i64x2 d_hi = mul_hi(ux, uy) - via - load2u(areas + j + 2);

                i64x2 p_lo = {base_i | j, base_i | (j + 1)};
                i64x2 p_hi = {base_i | (j + 2), base_i | (j + 3)};

                auto c_lo = (d_lo > best_d);
                best_d = c_lo ? d_lo : best_d;
                best_pair = c_lo ? p_lo : best_pair;

                auto c_hi = (d_hi > best_d);
                best_d = c_hi ? d_hi : best_d;
                best_pair = c_hi ? p_hi : best_pair;
            }
        }

        int64_t win_pair = (best_d[1] > best_d[0]) ? best_pair[1] : best_pair[0];
        int seed1 = static_cast<int>(win_pair >> 8);
        int seed2 = static_cast<int>(win_pair & 0xFF);

        // 2. Initialize groups
        int32_t g1_x0 = ex0[seed1], g1_x1 = ex1[seed1], g1_y0 = ey0[seed1], g1_y1 = ey1[seed1];
        int64_t g1_area = areas[seed1];
        uint32_t c1 = 1;
        n1.x0[0] = g1_x0; n1.x1[0] = g1_x1; n1.y0[0] = g1_y0; n1.y1[0] = g1_y1; n1.val[0] = eval[seed1];

        int32_t g2_x0 = ex0[seed2], g2_x1 = ex1[seed2], g2_y0 = ey0[seed2], g2_y1 = ey1[seed2];
        int64_t g2_area = areas[seed2];
        uint32_t c2 = 1;
        n2.x0[0] = g2_x0; n2.x1[0] = g2_x1; n2.y0[0] = g2_y0; n2.y1[0] = g2_y1; n2.val[0] = eval[seed2];

        // Compact remaining 15 entries for contiguous vector-friendly PickNext updates
        int32_t rx0[16], rx1[16], ry0[16], ry1[16], rval[16];
        int n_rem = 0;
        for (int i = 0; i < 17; ++i) {
            if (i != seed1 && i != seed2) {
                rx0[n_rem] = ex0[i];
                rx1[n_rem] = ex1[i];
                ry0[n_rem] = ey0[i];
                ry1[n_rem] = ey1[i];
                rval[n_rem] = eval[i];
                ++n_rem;
            }
        }

        int64_t d1_arr[16], d2_arr[16];
        for (int k = 0; k < n_rem; ++k) {
            int32_t ux0 = g1_x0 < rx0[k] ? g1_x0 : rx0[k];
            int32_t ux1 = g1_x1 > rx1[k] ? g1_x1 : rx1[k];
            int32_t uy0 = g1_y0 < ry0[k] ? g1_y0 : ry0[k];
            int32_t uy1 = g1_y1 > ry1[k] ? g1_y1 : ry1[k];
            d1_arr[k] = static_cast<int64_t>(ux1 - ux0) * static_cast<int64_t>(uy1 - uy0) - g1_area;

            int32_t vx0 = g2_x0 < rx0[k] ? g2_x0 : rx0[k];
            int32_t vx1 = g2_x1 > rx1[k] ? g2_x1 : rx1[k];
            int32_t vy0 = g2_y0 < ry0[k] ? g2_y0 : ry0[k];
            int32_t vy1 = g2_y1 > ry1[k] ? g2_y1 : ry1[k];
            d2_arr[k] = static_cast<int64_t>(vx1 - vx0) * static_cast<int64_t>(vy1 - vy0) - g2_area;
        }

        while (n_rem > 0) {
            if (c1 + static_cast<uint32_t>(n_rem) == MIN_ENTRIES) {
                for (int k = 0; k < n_rem; ++k) {
                    n1.x0[c1] = rx0[k]; n1.x1[c1] = rx1[k];
                    n1.y0[c1] = ry0[k]; n1.y1[c1] = ry1[k];
                    n1.val[c1] = rval[k];
                    ++c1;
                    if (rx0[k] < g1_x0) g1_x0 = rx0[k];
                    if (rx1[k] > g1_x1) g1_x1 = rx1[k];
                    if (ry0[k] < g1_y0) g1_y0 = ry0[k];
                    if (ry1[k] > g1_y1) g1_y1 = ry1[k];
                }
                break;
            }
            if (c2 + static_cast<uint32_t>(n_rem) == MIN_ENTRIES) {
                for (int k = 0; k < n_rem; ++k) {
                    n2.x0[c2] = rx0[k]; n2.x1[c2] = rx1[k];
                    n2.y0[c2] = ry0[k]; n2.y1[c2] = ry1[k];
                    n2.val[c2] = rval[k];
                    ++c2;
                    if (rx0[k] < g2_x0) g2_x0 = rx0[k];
                    if (rx1[k] > g2_x1) g2_x1 = rx1[k];
                    if (ry0[k] < g2_y0) g2_y0 = ry0[k];
                    if (ry1[k] > g2_y1) g2_y1 = ry1[k];
                }
                break;
            }

            int best_k = 0;
            int64_t best_diff = std::llabs(d1_arr[0] - d2_arr[0]);
            for (int k = 1; k < n_rem; ++k) {
                int64_t diff = std::llabs(d1_arr[k] - d2_arr[k]);
                if (diff > best_diff) {
                    best_diff = diff;
                    best_k = k;
                }
            }

            int64_t d1 = d1_arr[best_k];
            int64_t d2 = d2_arr[best_k];
            int32_t cx0 = rx0[best_k], cx1 = rx1[best_k];
            int32_t cy0 = ry0[best_k], cy1 = ry1[best_k];
            int32_t cval = rval[best_k];

            --n_rem;
            rx0[best_k] = rx0[n_rem];
            rx1[best_k] = rx1[n_rem];
            ry0[best_k] = ry0[n_rem];
            ry1[best_k] = ry1[n_rem];
            rval[best_k] = rval[n_rem];
            d1_arr[best_k] = d1_arr[n_rem];
            d2_arr[best_k] = d2_arr[n_rem];

            bool to_g1;
            if (d1 != d2) {
                to_g1 = (d1 < d2);
            } else if (g1_area != g2_area) {
                to_g1 = (g1_area < g2_area);
            } else {
                to_g1 = (c1 <= c2);
            }

            if (to_g1) {
                n1.x0[c1] = cx0; n1.x1[c1] = cx1;
                n1.y0[c1] = cy0; n1.y1[c1] = cy1;
                n1.val[c1] = cval;
                ++c1;
                int32_t nx0 = cx0 < g1_x0 ? cx0 : g1_x0;
                int32_t nx1 = cx1 > g1_x1 ? cx1 : g1_x1;
                int32_t ny0 = cy0 < g1_y0 ? cy0 : g1_y0;
                int32_t ny1 = cy1 > g1_y1 ? cy1 : g1_y1;
                if (nx0 != g1_x0 || nx1 != g1_x1 || ny0 != g1_y0 || ny1 != g1_y1) {
                    g1_x0 = nx0; g1_x1 = nx1; g1_y0 = ny0; g1_y1 = ny1;
                    g1_area = static_cast<int64_t>(g1_x1 - g1_x0) * static_cast<int64_t>(g1_y1 - g1_y0);
                    for (int k = 0; k < n_rem; ++k) {
                        int32_t ux0 = g1_x0 < rx0[k] ? g1_x0 : rx0[k];
                        int32_t ux1 = g1_x1 > rx1[k] ? g1_x1 : rx1[k];
                        int32_t uy0 = g1_y0 < ry0[k] ? g1_y0 : ry0[k];
                        int32_t uy1 = g1_y1 > ry1[k] ? g1_y1 : ry1[k];
                        d1_arr[k] = static_cast<int64_t>(ux1 - ux0) * static_cast<int64_t>(uy1 - uy0) - g1_area;
                    }
                }
            } else {
                n2.x0[c2] = cx0; n2.x1[c2] = cx1;
                n2.y0[c2] = cy0; n2.y1[c2] = cy1;
                n2.val[c2] = cval;
                ++c2;
                int32_t nx0 = cx0 < g2_x0 ? cx0 : g2_x0;
                int32_t nx1 = cx1 > g2_x1 ? cx1 : g2_x1;
                int32_t ny0 = cy0 < g2_y0 ? cy0 : g2_y0;
                int32_t ny1 = cy1 > g2_y1 ? cy1 : g2_y1;
                if (nx0 != g2_x0 || nx1 != g2_x1 || ny0 != g2_y0 || ny1 != g2_y1) {
                    g2_x0 = nx0; g2_x1 = nx1; g2_y0 = ny0; g2_y1 = ny1;
                    g2_area = static_cast<int64_t>(g2_x1 - g2_x0) * static_cast<int64_t>(g2_y1 - g2_y0);
                    for (int k = 0; k < n_rem; ++k) {
                        int32_t vx0 = g2_x0 < rx0[k] ? g2_x0 : rx0[k];
                        int32_t vx1 = g2_x1 > rx1[k] ? g2_x1 : rx1[k];
                        int32_t vy0 = g2_y0 < ry0[k] ? g2_y0 : ry0[k];
                        int32_t vy1 = g2_y1 > ry1[k] ? g2_y1 : ry1[k];
                        d2_arr[k] = static_cast<int64_t>(vx1 - vx0) * static_cast<int64_t>(vy1 - vy0) - g2_area;
                    }
                }
            }
        }

        n1.count = c1;
        for (uint32_t i = c1; i < MAX_ENTRIES; ++i) {
            n1.x0[i] = SENTINEL_MAX; n1.x1[i] = SENTINEL_MIN;
            n1.y0[i] = SENTINEL_MAX; n1.y1[i] = SENTINEL_MIN;
        }
        n2.count = c2;
        for (uint32_t i = c2; i < MAX_ENTRIES; ++i) {
            n2.x0[i] = SENTINEL_MAX; n2.x1[i] = SENTINEL_MIN;
            n2.y0[i] = SENTINEL_MAX; n2.y1[i] = SENTINEL_MIN;
        }
        b1_out = {g1_x0, g1_y0, g1_x1, g1_y1};
        b2_out = {g2_x0, g2_y0, g2_x1, g2_y1};
    }

    void insert_at_level(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t val,
                         uint32_t target_level) {
        uint32_t path_node[MAX_HEIGHT];
        uint8_t path_slot[MAX_HEIGHT];
        uint32_t path_len = 0;

        uint32_t cur = root_;
        uint32_t cur_level = height_ - 1;
        while (cur_level > target_level) {
            const Node& n = internal_nodes_[cur];
            uint32_t best = choose_subtree(n, x0, y0, x1, y1);
            path_node[path_len] = cur;
            path_slot[path_len] = static_cast<uint8_t>(best);
            ++path_len;
            cur = static_cast<uint32_t>(n.val[best]);
            --cur_level;
        }

        Node& target = (target_level == 0) ? leaf_nodes_[cur] : internal_nodes_[cur];

        if (target.count < MAX_ENTRIES) [[likely]] {
            uint32_t c = target.count++;
            target.x0[c] = x0;
            target.x1[c] = x1;
            target.y0[c] = y0;
            target.y1[c] = y1;
            target.val[c] = val;

            for (int d = static_cast<int>(path_len) - 1; d >= 0; --d) {
                Node& p = internal_nodes_[path_node[d]];
                uint32_t s = path_slot[d];
                int32_t ox0 = p.x0[s], ox1 = p.x1[s], oy0 = p.y0[s], oy1 = p.y1[s];
                int32_t nx0 = x0 < ox0 ? x0 : ox0;
                int32_t nx1 = x1 > ox1 ? x1 : ox1;
                int32_t ny0 = y0 < oy0 ? y0 : oy0;
                int32_t ny1 = y1 > oy1 ? y1 : oy1;
                if (nx0 == ox0 && nx1 == ox1 && ny0 == oy0 && ny1 == oy1) break;
                p.x0[s] = nx0;
                p.x1[s] = nx1;
                p.y0[s] = ny0;
                p.y1[s] = ny1;
            }
            return;
        }

        uint32_t sib;
        Rect b1, b2;
        if (target_level == 0) {
            sib = leaf_nodes_.alloc();
            quadratic_split(leaf_nodes_[cur], leaf_nodes_[sib], x0, y0, x1, y1, val, b1, b2);
        } else {
            sib = internal_nodes_.alloc();
            quadratic_split(internal_nodes_[cur], internal_nodes_[sib], x0, y0, x1, y1, val, b1, b2);
        }

        uint32_t split_child1 = cur;
        uint32_t split_child2 = sib;

        for (int d = static_cast<int>(path_len) - 1; d >= 0; --d) {
            uint32_t p_idx = path_node[d];
            uint32_t s = path_slot[d];
            Node& p = internal_nodes_[p_idx];
            p.x0[s] = b1.x0;
            p.x1[s] = b1.x1;
            p.y0[s] = b1.y0;
            p.y1[s] = b1.y1;

            if (p.count < MAX_ENTRIES) {
                uint32_t c = p.count++;
                p.x0[c] = b2.x0;
                p.x1[c] = b2.x1;
                p.y0[c] = b2.y0;
                p.y1[c] = b2.y1;
                p.val[c] = static_cast<int32_t>(split_child2);

                for (int u = d - 1; u >= 0; --u) {
                    Node& anc = internal_nodes_[path_node[u]];
                    uint32_t as = path_slot[u];
                    int32_t ox0 = anc.x0[as], ox1 = anc.x1[as], oy0 = anc.y0[as], oy1 = anc.y1[as];
                    int32_t nx0 = x0 < ox0 ? x0 : ox0;
                    int32_t nx1 = x1 > ox1 ? x1 : ox1;
                    int32_t ny0 = y0 < oy0 ? y0 : oy0;
                    int32_t ny1 = y1 > oy1 ? y1 : oy1;
                    if (nx0 == ox0 && nx1 == ox1 && ny0 == oy0 && ny1 == oy1) break;
                    anc.x0[as] = nx0;
                    anc.x1[as] = nx1;
                    anc.y0[as] = ny0;
                    anc.y1[as] = ny1;
                }
                return;
            }

            uint32_t p_sib = internal_nodes_.alloc();
            Rect pb1, pb2;
            quadratic_split(internal_nodes_[p_idx], internal_nodes_[p_sib],
                            b2.x0, b2.y0, b2.x1, b2.y1, static_cast<int32_t>(split_child2),
                            pb1, pb2);
            split_child1 = p_idx;
            split_child2 = p_sib;
            b1 = pb1;
            b2 = pb2;
        }

        uint32_t new_root = internal_nodes_.alloc();
        init_node_pair(internal_nodes_[new_root],
                       b1, static_cast<int32_t>(split_child1),
                       b2, static_cast<int32_t>(split_child2));
        root_ = new_root;
        ++height_;
    }

    // --------------------------------------------------------- remove helpers

    __attribute__((noinline)) void propagate_shrink(const uint32_t* path_node,
                                                    const uint8_t* path_slot,
                                                    uint32_t parent_depth, uint32_t child_slot,
                                                    Rect new_bbox) {
        int d = static_cast<int>(parent_depth);
        uint32_t s = child_slot;
        while (true) {
            Node& p = internal_nodes_[path_node[d]];
            int32_t ox0 = p.x0[s], ox1 = p.x1[s], oy0 = p.y0[s], oy1 = p.y1[s];
            p.x0[s] = new_bbox.x0;
            p.x1[s] = new_bbox.x1;
            p.y0[s] = new_bbox.y0;
            p.y1[s] = new_bbox.y1;
            if (d == 0) return;

            Node& gp = internal_nodes_[path_node[d - 1]];
            uint32_t gs = path_slot[d];
            if (ox0 > gp.x0[gs] && ox1 < gp.x1[gs] && oy0 > gp.y0[gs] && oy1 < gp.y1[gs]) {
                return;
            }
            Rect pb = compute_bbox(p);
            if (pb.x0 == gp.x0[gs] && pb.x1 == gp.x1[gs] &&
                pb.y0 == gp.y0[gs] && pb.y1 == gp.y1[gs]) {
                return;
            }
            new_bbox = pb;
            --d;
            s = gs;
        }
    }

    __attribute__((noinline)) void condense_and_reinsert(const uint32_t* path_node,
                                                         const uint8_t* path_slot,
                                                         uint32_t h) {
        struct Orphan {
            int32_t x0, y0, x1, y1, val;
            uint8_t level;
        };
        Orphan orphans[MAX_HEIGHT * MIN_ENTRIES];
        uint32_t n_orphans = 0;

        for (int d = static_cast<int>(h) - 1; d >= 1; --d) {
            uint32_t lvl = (h - 1) - static_cast<uint32_t>(d);
            uint32_t u = path_node[d];
            uint32_t p_idx = path_node[d - 1];
            uint32_t ps = path_slot[d];
            Node& n = (lvl == 0) ? leaf_nodes_[u] : internal_nodes_[u];
            Node& p = internal_nodes_[p_idx];

            if (n.count < MIN_ENTRIES) {
                uint32_t c = n.count;
                for (uint32_t i = 0; i < c; ++i) {
                    orphans[n_orphans++] = {n.x0[i], n.y0[i], n.x1[i], n.y1[i], n.val[i],
                                            static_cast<uint8_t>(lvl)};
                }
                remove_slot(p, ps);
                if (lvl == 0) {
                    leaf_nodes_.free(u);
                } else {
                    internal_nodes_.free(u);
                }
            } else {
                Rect nb = compute_bbox(n);
                if (nb.x0 == p.x0[ps] && nb.x1 == p.x1[ps] &&
                    nb.y0 == p.y0[ps] && nb.y1 == p.y1[ps]) {
                    break;
                }
                propagate_shrink(path_node, path_slot, static_cast<uint32_t>(d - 1), ps, nb);
                break;
            }
        }

        for (int i = static_cast<int>(n_orphans) - 1; i >= 0; --i) {
            const Orphan& o = orphans[i];
            insert_at_level(o.x0, o.y0, o.x1, o.y1, o.val, o.level);
        }

        while (height_ > 1 && internal_nodes_[root_].count == 1) {
            uint32_t old_root = root_;
            root_ = static_cast<uint32_t>(internal_nodes_[old_root].val[0]);
            internal_nodes_.free(old_root);
            --height_;
        }
    }

    // --------------------------------------------------------- nearest helpers

    void heap_push(Cand c) const {
        std::size_t i = heap_.size();
        heap_.push_back(c);
        Cand* data = heap_.data();
        while (i > 0) {
            std::size_t p = (i - 1) >> 2;
            if (data[p].key <= c.key) break;
            data[i] = data[p];
            i = p;
        }
        data[i] = c;
    }

    void heap_pop() const {
        Cand last = heap_.back();
        heap_.pop_back();
        std::size_t n = heap_.size();
        if (n == 0) return;
        Cand* data = heap_.data();
        std::size_t i = 0;
        while (true) {
            std::size_t c0 = (i << 2) + 1;
            if (c0 >= n) break;
            std::size_t best = c0;
            uint64_t best_key = data[c0].key;
            std::size_t c_end = std::min(c0 + 4, n);
            for (std::size_t c = c0 + 1; c < c_end; ++c) {
                if (data[c].key < best_key) {
                    best_key = data[c].key;
                    best = c;
                }
            }
            if (last.key <= best_key) break;
            data[i] = data[best];
            i = best;
        }
        data[i] = last;
    }

    static inline bool res_worse(const ResItem& a, const ResItem& b) {
        return a.dist > b.dist || (a.dist == b.dist && a.id > b.id);
    }

    static inline void res_push(ResItem* h, std::size_t& sz, ResItem item) {
        std::size_t i = sz++;
        while (i > 0) {
            std::size_t p = (i - 1) >> 1;
            if (!res_worse(item, h[p])) break;
            h[i] = h[p];
            i = p;
        }
        h[i] = item;
    }

    static inline void res_sift_down(ResItem* h, std::size_t sz, std::size_t i, ResItem item) {
        while (true) {
            std::size_t l = (i << 1) + 1;
            if (l >= sz) break;
            std::size_t best = l;
            std::size_t r = l + 1;
            if (r < sz && res_worse(h[r], h[l])) best = r;
            if (!res_worse(h[best], item)) break;
            h[i] = h[best];
            i = best;
        }
        h[i] = item;
    }

    static inline uint32_t dist_filter16(const Node& n, i32x4 vpx, i32x4 vpy, i32x4 vr,
                                         int32_t* dx_out, int32_t* dy_out) {
        constexpr i32x4 vzero = {0, 0, 0, 0};

        i32x4 dx0 = vmax4(vmax4(load4(n.x0 + 0) - vpx, vpx - load4(n.x1 + 0)), vzero);
        i32x4 dx1 = vmax4(vmax4(load4(n.x0 + 4) - vpx, vpx - load4(n.x1 + 4)), vzero);
        i32x4 dx2 = vmax4(vmax4(load4(n.x0 + 8) - vpx, vpx - load4(n.x1 + 8)), vzero);
        i32x4 dx3 = vmax4(vmax4(load4(n.x0 + 12) - vpx, vpx - load4(n.x1 + 12)), vzero);

        i32x4 mx0 = (dx0 <= vr);
        i32x4 mx1 = (dx1 <= vr);
        i32x4 mx2 = (dx2 <= vr);
        i32x4 mx3 = (dx3 <= vr);
        if (!any_nonzero16(mx0, mx1, mx2, mx3)) return 0;

        i32x4 dy0 = vmax4(vmax4(load4(n.y0 + 0) - vpy, vpy - load4(n.y1 + 0)), vzero);
        i32x4 dy1 = vmax4(vmax4(load4(n.y0 + 4) - vpy, vpy - load4(n.y1 + 4)), vzero);
        i32x4 dy2 = vmax4(vmax4(load4(n.y0 + 8) - vpy, vpy - load4(n.y1 + 8)), vzero);
        i32x4 dy3 = vmax4(vmax4(load4(n.y0 + 12) - vpy, vpy - load4(n.y1 + 12)), vzero);

        i32x4 m0 = mx0 & (dy0 <= vr);
        i32x4 m1 = mx1 & (dy1 <= vr);
        i32x4 m2 = mx2 & (dy2 <= vr);
        i32x4 m3 = mx3 & (dy3 <= vr);
        uint32_t mask = pack_mask16(m0, m1, m2, m3);
        if (mask == 0) return 0;

        store4(dx_out + 0, dx0);
        store4(dx_out + 4, dx1);
        store4(dx_out + 8, dx2);
        store4(dx_out + 12, dx3);
        store4(dy_out + 0, dy0);
        store4(dy_out + 4, dy1);
        store4(dy_out + 8, dy2);
        store4(dy_out + 12, dy3);
        return mask;
    }

    std::size_t nearest_one(int32_t px, int32_t py, int32_t* out_ids) const {
        const i32x4 vpx = {px, px, px, px};
        const i32x4 vpy = {py, py, py, py};
        uint64_t best_dist = INF_DIST;
        int32_t best_id = std::numeric_limits<int32_t>::max();
        int32_t r = INF_RADIUS;
        i32x4 vr = {r, r, r, r};

        alignas(16) int32_t dx[16], dy[16];

        if (height_ == 1) [[unlikely]] {
            const Node& leaf = leaf_nodes_[root_];
            uint32_t mask = dist_filter16(leaf, vpx, vpy, vr, dx, dy);
            while (mask) {
                uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                mask &= mask - 1;
                uint64_t d = static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) *
                                 static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) +
                             static_cast<uint64_t>(static_cast<uint32_t>(dy[i])) *
                                 static_cast<uint64_t>(static_cast<uint32_t>(dy[i]));
                if (d < best_dist || (d == best_dist && leaf.val[i] < best_id)) {
                    best_dist = d;
                    best_id = leaf.val[i];
                }
            }
            out_ids[0] = best_id;
            return 1;
        }

        heap_.clear();
        uint32_t cur_node = root_;
        uint32_t cur_level = height_ - 1;

        while (true) {
            if (cur_level == 0) {
                const Node& leaf = leaf_nodes_[cur_node];
                uint32_t mask = dist_filter16(leaf, vpx, vpy, vr, dx, dy);
                while (mask) {
                    uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                    mask &= mask - 1;
                    uint64_t d = static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) *
                                     static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) +
                                 static_cast<uint64_t>(static_cast<uint32_t>(dy[i])) *
                                     static_cast<uint64_t>(static_cast<uint32_t>(dy[i]));
                    if (d < best_dist || (d == best_dist && leaf.val[i] < best_id)) {
                        if (d < best_dist) {
                            best_dist = d;
                            r = isqrt_floor(best_dist);
                            vr = {r, r, r, r};
                        }
                        best_id = leaf.val[i];
                    }
                }
                if (heap_.empty() || (heap_[0].key >> LEVEL_BITS) > best_dist) break;
                cur_node = heap_[0].node;
                cur_level = static_cast<uint32_t>(heap_[0].key & LEVEL_MASK);
                heap_pop();
            } else {
                const Node& n = internal_nodes_[cur_node];
                uint32_t mask = dist_filter16(n, vpx, vpy, vr, dx, dy);
                uint64_t c_dist[16];
                uint32_t c_node[16];
                int cnt = 0;
                int best_idx = 0;
                uint64_t min_cd = INF_DIST;

                while (mask) {
                    uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                    mask &= mask - 1;
                    uint64_t d = static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) *
                                     static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) +
                                 static_cast<uint64_t>(static_cast<uint32_t>(dy[i])) *
                                     static_cast<uint64_t>(static_cast<uint32_t>(dy[i]));
                    if (d <= best_dist) {
                        if (d < min_cd) {
                            min_cd = d;
                            best_idx = cnt;
                        }
                        c_dist[cnt] = d;
                        c_node[cnt] = static_cast<uint32_t>(n.val[i]);
                        ++cnt;
                    }
                }

                if (cnt == 0) {
                    if (heap_.empty() || (heap_[0].key >> LEVEL_BITS) > best_dist) break;
                    cur_node = heap_[0].node;
                    cur_level = static_cast<uint32_t>(heap_[0].key & LEVEL_MASK);
                    heap_pop();
                } else {
                    uint32_t next_level = cur_level - 1;
                    uint64_t best_key = (c_dist[best_idx] << LEVEL_BITS) | next_level;
                    uint32_t best_child = c_node[best_idx];
                    for (int j = 0; j < cnt; ++j) {
                        if (j != best_idx) {
                            heap_push({(c_dist[j] << LEVEL_BITS) | next_level, c_node[j]});
                        }
                    }
                    if (heap_.empty() || best_key <= heap_[0].key) {
                        cur_node = best_child;
                        cur_level = next_level;
                    } else {
                        heap_push({best_key, best_child});
                        if ((heap_[0].key >> LEVEL_BITS) > best_dist) break;
                        cur_node = heap_[0].node;
                        cur_level = static_cast<uint32_t>(heap_[0].key & LEVEL_MASK);
                        heap_pop();
                    }
                }
            }
        }

        out_ids[0] = best_id;
        return 1;
    }

    std::size_t nearest_k(int32_t px, int32_t py, std::size_t target, int32_t* out_ids) const {
        const i32x4 vpx = {px, px, px, px};
        const i32x4 vpy = {py, py, py, py};

        ResItem stack_res[32];
        ResItem* res = stack_res;
        if (target > 32) [[unlikely]] {
            if (res_vec_.size() < target) res_vec_.resize(target);
            res = res_vec_.data();
        }
        std::size_t res_count = 0;

        uint64_t tau_dist = INF_DIST;
        int32_t tau_id = std::numeric_limits<int32_t>::max();
        int32_t r = INF_RADIUS;
        i32x4 vr = {r, r, r, r};

        alignas(16) int32_t dx[16], dy[16];

        if (height_ == 1) [[unlikely]] {
            const Node& leaf = leaf_nodes_[root_];
            uint32_t mask = dist_filter16(leaf, vpx, vpy, vr, dx, dy);
            while (mask) {
                uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                mask &= mask - 1;
                uint64_t d = static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) *
                                 static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) +
                             static_cast<uint64_t>(static_cast<uint32_t>(dy[i])) *
                                 static_cast<uint64_t>(static_cast<uint32_t>(dy[i]));
                int32_t id = leaf.val[i];
                if (res_count < target) {
                    res_push(res, res_count, {d, id});
                    if (res_count == target) {
                        tau_dist = res[0].dist;
                        tau_id = res[0].id;
                    }
                } else if (d < tau_dist || (d == tau_dist && id < tau_id)) {
                    res_sift_down(res, res_count, 0, {d, id});
                    tau_dist = res[0].dist;
                    tau_id = res[0].id;
                }
            }
        } else {
            heap_.clear();
            uint32_t cur_node = root_;
            uint32_t cur_level = height_ - 1;

            while (true) {
                if (cur_level == 0) {
                    const Node& leaf = leaf_nodes_[cur_node];
                    uint32_t mask = dist_filter16(leaf, vpx, vpy, vr, dx, dy);
                    while (mask) {
                        uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                        mask &= mask - 1;
                        uint64_t d = static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) *
                                         static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) +
                                     static_cast<uint64_t>(static_cast<uint32_t>(dy[i])) *
                                         static_cast<uint64_t>(static_cast<uint32_t>(dy[i]));
                        int32_t id = leaf.val[i];
                        if (res_count < target) {
                            res_push(res, res_count, {d, id});
                            if (res_count == target) {
                                tau_dist = res[0].dist;
                                tau_id = res[0].id;
                                r = isqrt_floor(tau_dist);
                                vr = {r, r, r, r};
                            }
                        } else if (d < tau_dist || (d == tau_dist && id < tau_id)) {
                            res_sift_down(res, res_count, 0, {d, id});
                            if (res[0].dist != tau_dist) {
                                tau_dist = res[0].dist;
                                r = isqrt_floor(tau_dist);
                                vr = {r, r, r, r};
                            }
                            tau_id = res[0].id;
                        }
                    }
                    if (heap_.empty() || (heap_[0].key >> LEVEL_BITS) > tau_dist) break;
                    cur_node = heap_[0].node;
                    cur_level = static_cast<uint32_t>(heap_[0].key & LEVEL_MASK);
                    heap_pop();
                } else {
                    const Node& n = internal_nodes_[cur_node];
                    uint32_t mask = dist_filter16(n, vpx, vpy, vr, dx, dy);
                    uint64_t c_dist[16];
                    uint32_t c_node[16];
                    int cnt = 0;
                    int best_idx = 0;
                    uint64_t min_cd = INF_DIST;

                    while (mask) {
                        uint32_t i = static_cast<uint32_t>(__builtin_ctz(mask));
                        mask &= mask - 1;
                        uint64_t d = static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) *
                                         static_cast<uint64_t>(static_cast<uint32_t>(dx[i])) +
                                     static_cast<uint64_t>(static_cast<uint32_t>(dy[i])) *
                                         static_cast<uint64_t>(static_cast<uint32_t>(dy[i]));
                        if (d <= tau_dist) {
                            if (d < min_cd) {
                                min_cd = d;
                                best_idx = cnt;
                            }
                            c_dist[cnt] = d;
                            c_node[cnt] = static_cast<uint32_t>(n.val[i]);
                            ++cnt;
                        }
                    }

                    if (cnt == 0) {
                        if (heap_.empty() || (heap_[0].key >> LEVEL_BITS) > tau_dist) break;
                        cur_node = heap_[0].node;
                        cur_level = static_cast<uint32_t>(heap_[0].key & LEVEL_MASK);
                        heap_pop();
                    } else {
                        uint32_t next_level = cur_level - 1;
                        uint64_t best_key = (c_dist[best_idx] << LEVEL_BITS) | next_level;
                        uint32_t best_child = c_node[best_idx];
                        for (int j = 0; j < cnt; ++j) {
                            if (j != best_idx) {
                                heap_push({(c_dist[j] << LEVEL_BITS) | next_level, c_node[j]});
                            }
                        }
                        if (heap_.empty() || best_key <= heap_[0].key) {
                            cur_node = best_child;
                            cur_level = next_level;
                        } else {
                            heap_push({best_key, best_child});
                            if ((heap_[0].key >> LEVEL_BITS) > tau_dist) break;
                            cur_node = heap_[0].node;
                            cur_level = static_cast<uint32_t>(heap_[0].key & LEVEL_MASK);
                            heap_pop();
                        }
                    }
                }
            }
        }

        std::size_t sz = res_count;
        for (std::size_t out_i = sz; out_i > 0; --out_i) {
            out_ids[out_i - 1] = res[0].id;
            --sz;
            if (sz > 0) {
                res_sift_down(res, sz, 0, res[sz]);
            }
        }
        return res_count;
    }
};
