#pragma once

#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <new>
#include <optional>
#include <vector>

class BTree {
public:
    BTree() noexcept = default;

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

    ~BTree() noexcept {
        for (LeafNode* chunk : leaf_chunks_) {
            ::operator delete(chunk, std::align_val_t{CACHE_LINE});
        }
        if (internals_ != nullptr) {
            ::operator delete(internals_, std::align_val_t{CACHE_LINE});
        }
    }

    bool insert(std::int64_t key, std::int64_t value) {
        std::uint32_t h = height_;
        if (h == 0) [[unlikely]] {
            std::uint32_t id = alloc_leaf();
            LeafNode& leaf = leaf_at(id);
            leaf.keys[0] = key;
            leaf.vals[0] = value;
            leaf.count = 1;
            fill_sentinels(leaf.keys, 1);
            root_ = id;
            height_ = 1;
            len_ = 1;
            return true;
        }

        PathFrame path[MAX_HEIGHT];
        std::uint32_t depth = 0;
        std::uint32_t id = root_;

        for (std::uint32_t rem = h - 1; rem > 0; --rem) {
            InternalNode& node = internals_[id];
            std::uint32_t pos = search_keys(node.keys, key);
            std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
            if ((pos < node.count) & (node.keys[safe_pos] == key)) [[unlikely]] {
                node.vals[pos] = value;
                return false;
            }
            path[depth++] = {id, pos};
            id = node.children[pos];
        }

        LeafNode& leaf = leaf_at(id);
        std::uint32_t pos = search_keys(leaf.keys, key);
        std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
        if ((pos < leaf.count) & (leaf.keys[safe_pos] == key)) {
            leaf.vals[pos] = value;
            return false;
        }

        ++len_;
        std::uint32_t cnt = leaf.count;
        if (cnt < MAX_KEYS) [[likely]] {
            if (pos < cnt) {
                std::memmove(leaf.keys + pos + 1, leaf.keys + pos,
                             static_cast<std::size_t>(cnt - pos) * sizeof(std::int64_t));
                std::memmove(leaf.vals + pos + 1, leaf.vals + pos,
                             static_cast<std::size_t>(cnt - pos) * sizeof(std::int64_t));
            }
            leaf.keys[pos] = key;
            leaf.vals[pos] = value;
            leaf.count = cnt + 1;
            return true;
        }

        insert_split_leaf(id, pos, key, value, path, depth);
        return true;
    }

    std::optional<std::int64_t> get(std::int64_t key) const noexcept {
        std::uint32_t h = height_;
        if (h == 0) [[unlikely]] {
            return std::nullopt;
        }

        std::uint32_t id = root_;
        for (std::uint32_t rem = h - 1; rem > 0; --rem) {
            const InternalNode& node = internals_[id];
            std::uint32_t pos = search_keys(node.keys, key);
            std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
            if ((pos < node.count) & (node.keys[safe_pos] == key)) [[unlikely]] {
                return node.vals[pos];
            }
            id = node.children[pos];
        }

        const LeafNode& leaf = leaf_at(id);
        std::uint32_t pos = search_keys(leaf.keys, key);
        std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
        if ((pos < leaf.count) & (leaf.keys[safe_pos] == key)) {
            return leaf.vals[pos];
        }
        return std::nullopt;
    }

    bool remove(std::int64_t key) noexcept {
        std::uint32_t h = height_;
        if (h == 0) [[unlikely]] {
            return false;
        }

        if (h == 1) [[unlikely]] {
            LeafNode& leaf = leaf_at(root_);
            std::uint32_t pos = search_keys(leaf.keys, key);
            std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
            if (!((pos < leaf.count) & (leaf.keys[safe_pos] == key))) {
                return false;
            }
            std::uint32_t n = leaf.count - 1;
            if (pos < n) {
                std::memmove(leaf.keys + pos, leaf.keys + pos + 1,
                             static_cast<std::size_t>(n - pos) * sizeof(std::int64_t));
                std::memmove(leaf.vals + pos, leaf.vals + pos + 1,
                             static_cast<std::size_t>(n - pos) * sizeof(std::int64_t));
            }
            leaf.count = n;
            leaf.keys[n] = SENTINEL;
            --len_;
            if (n == 0) {
                free_leaf(root_);
                root_ = INVALID_ID;
                height_ = 0;
            }
            return true;
        }

        PathFrame path[MAX_HEIGHT];
        std::uint32_t depth = 0;
        std::uint32_t id = root_;

        for (std::uint32_t rem = h - 1; rem > 0; --rem) {
            InternalNode& node = internals_[id];
            std::uint32_t pos = search_keys(node.keys, key);
            std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
            if ((pos < node.count) & (node.keys[safe_pos] == key)) [[unlikely]] {
                // Replace with in-order predecessor (rightmost entry of children[pos]).
                std::uint32_t target_id = id;
                std::uint32_t target_pos = pos;
                path[depth++] = {id, pos};
                id = node.children[pos];
                for (std::uint32_t down = rem - 1; down > 0; --down) {
                    InternalNode& cur = internals_[id];
                    std::uint32_t rpos = cur.count;
                    path[depth++] = {id, rpos};
                    id = cur.children[rpos];
                }
                LeafNode& pred_leaf = leaf_at(id);
                std::uint32_t last = pred_leaf.count - 1;
                InternalNode& target = internals_[target_id];
                target.keys[target_pos] = pred_leaf.keys[last];
                target.vals[target_pos] = pred_leaf.vals[last];
                pred_leaf.count = last;
                pred_leaf.keys[last] = SENTINEL;
                --len_;
                if (last < MIN_KEYS) [[unlikely]] {
                    rebalance_leaf(id, path, depth);
                }
                return true;
            }
            path[depth++] = {id, pos};
            id = node.children[pos];
        }

        LeafNode& leaf = leaf_at(id);
        std::uint32_t pos = search_keys(leaf.keys, key);
        std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
        if (!((pos < leaf.count) & (leaf.keys[safe_pos] == key))) {
            return false;
        }

        std::uint32_t n = leaf.count - 1;
        if (pos < n) {
            std::memmove(leaf.keys + pos, leaf.keys + pos + 1,
                         static_cast<std::size_t>(n - pos) * sizeof(std::int64_t));
            std::memmove(leaf.vals + pos, leaf.vals + pos + 1,
                         static_cast<std::size_t>(n - pos) * sizeof(std::int64_t));
        }
        leaf.count = n;
        leaf.keys[n] = SENTINEL;
        --len_;
        if (n < MIN_KEYS) [[unlikely]] {
            rebalance_leaf(id, path, depth);
        }
        return true;
    }

    std::size_t range(std::int64_t lo, std::int64_t hi,
                      std::int64_t* out_keys, std::int64_t* out_vals,
                      std::size_t limit) const noexcept {
        if (lo > hi || limit == 0 || height_ == 0) [[unlikely]] {
            return 0;
        }
        std::size_t written = 0;
        if (height_ == 1) [[unlikely]] {
            emit_leaf_from(leaf_at(root_), lo, hi, out_keys, out_vals, limit, written);
            return written;
        }
        range_start(root_, height_ - 1, lo, hi, out_keys, out_vals, limit, written);
        return written;
    }

    std::size_t len() const noexcept { return len_; }
    std::size_t height() const noexcept { return height_; }

private:
    static constexpr std::size_t CACHE_LINE = 128;
    static constexpr std::uint32_t T = 16;
    static constexpr std::uint32_t MIN_KEYS = T - 1;      // 15
    static constexpr std::uint32_t MAX_KEYS = 2 * T - 1;  // 31
    static constexpr std::uint32_t MAX_CHILDREN = 2 * T;  // 32
    static constexpr std::uint32_t MAX_HEIGHT = 16;
    static constexpr std::uint32_t INVALID_ID = ~std::uint32_t{0};
    static constexpr std::int64_t SENTINEL = std::numeric_limits<std::int64_t>::max();

    static constexpr std::uint32_t LEAF_CHUNK_SHIFT = 11;
    static constexpr std::uint32_t LEAF_CHUNK_SIZE = 1u << LEAF_CHUNK_SHIFT;
    static constexpr std::uint32_t LEAF_CHUNK_MASK = LEAF_CHUNK_SIZE - 1;

    using i64x2 = std::int64_t __attribute__((vector_size(16)));

    struct alignas(CACHE_LINE) LeafNode {
        std::int64_t keys[MAX_KEYS];  // 0..247   (248 B)
        std::uint32_t count;          // 248..251 (4 B)
        std::uint32_t next_free;      // 252..255 (4 B)
        std::int64_t vals[MAX_KEYS];  // 256..503 (248 B)
        std::uint64_t pad_;           // 504..511 (8 B)
    };
    static_assert(sizeof(LeafNode) == 512);
    static_assert(alignof(LeafNode) == 128);
    static_assert(offsetof(LeafNode, vals) == 256);

    struct alignas(CACHE_LINE) InternalNode {
        std::int64_t keys[MAX_KEYS];           // 0..247   (248 B)
        std::uint32_t count;                   // 248..251 (4 B)
        std::uint32_t next_free;               // 252..255 (4 B)
        std::uint32_t children[MAX_CHILDREN];  // 256..383 (128 B)
        std::int64_t vals[MAX_KEYS];           // 384..631 (248 B)
        std::uint64_t pad_;                    // 632..639 (8 B)
    };
    static_assert(sizeof(InternalNode) == 640);
    static_assert(alignof(InternalNode) == 128);
    static_assert(offsetof(InternalNode, children) == 256);
    static_assert(offsetof(InternalNode, vals) == 384);

    struct PathFrame {
        std::uint32_t id;
        std::uint32_t pos;
    };

    // --------------------------------------------------------- node helpers

    static inline void fill_sentinels(std::int64_t* keys, std::uint32_t from) noexcept {
        for (std::uint32_t i = from; i < MAX_KEYS; ++i) {
            keys[i] = SENTINEL;
        }
    }

    static inline void fill_sentinels_range(std::int64_t* keys,
                                            std::uint32_t from,
                                            std::uint32_t to) noexcept {
        for (std::uint32_t i = from; i < to; ++i) {
            keys[i] = SENTINEL;
        }
    }

    // Branchless portable-SIMD lower_bound over 31 keys (unused slots hold INT64_MAX).
    // Returns index in [0, count] of first key >= `key`.
    static inline std::uint32_t search_keys(const std::int64_t* keys,
                                            std::int64_t key) noexcept {
        const i64x2 kv = {key, key};
        auto load = [keys](std::size_t idx) -> i64x2 {
            i64x2 v;
            std::memcpy(&v, keys + idx, 16);
            return v;
        };
        i64x2 a0 = (load(0) < kv);
        i64x2 a1 = (load(2) < kv);
        i64x2 a2 = (load(4) < kv);
        i64x2 a3 = (load(6) < kv);
        a0 += (load(8) < kv);
        a1 += (load(10) < kv);
        a2 += (load(12) < kv);
        a3 += (load(14) < kv);
        a0 += (load(16) < kv);
        a1 += (load(18) < kv);
        a2 += (load(20) < kv);
        a3 += (load(22) < kv);
        a0 += (load(24) < kv);
        a1 += (load(26) < kv);
        a2 += (load(28) < kv);
        std::uint32_t last = static_cast<std::uint32_t>(keys[30] < key);
        i64x2 sum = (a0 + a1) + (a2 + a3);
        return static_cast<std::uint32_t>(-(sum[0] + sum[1])) + last;
    }

    static inline void prefetch_leaf(const LeafNode* p) noexcept {
        const char* c = reinterpret_cast<const char*>(p);
        __builtin_prefetch(c, 0, 3);
        __builtin_prefetch(c + 128, 0, 3);
        __builtin_prefetch(c + 256, 0, 3);
        __builtin_prefetch(c + 384, 0, 3);
    }

    static inline void prefetch_internal(const InternalNode* p) noexcept {
        const char* c = reinterpret_cast<const char*>(p);
        __builtin_prefetch(c, 0, 3);
        __builtin_prefetch(c + 128, 0, 3);
        __builtin_prefetch(c + 256, 0, 3);
    }

    inline LeafNode& leaf_at(std::uint32_t id) noexcept {
        return leaf_chunks_[id >> LEAF_CHUNK_SHIFT][id & LEAF_CHUNK_MASK];
    }

    inline const LeafNode& leaf_at(std::uint32_t id) const noexcept {
        return leaf_chunks_[id >> LEAF_CHUNK_SHIFT][id & LEAF_CHUNK_MASK];
    }

    // -------------------------------------------------------- pool allocator

    std::uint32_t alloc_leaf() {
        if (leaf_free_head_ != INVALID_ID) {
            std::uint32_t id = leaf_free_head_;
            leaf_free_head_ = leaf_at(id).next_free;
            return id;
        }
        std::uint32_t id = leaf_count_;
        if (id < LEAF_CHUNK_SIZE) {
            if (id >= leaf_chunk0_cap_) [[unlikely]] {
                std::uint32_t new_cap = (leaf_chunk0_cap_ == 0) ? 16u : (leaf_chunk0_cap_ * 2u);
                LeafNode* mem = static_cast<LeafNode*>(
                    ::operator new(static_cast<std::size_t>(new_cap) * sizeof(LeafNode),
                                   std::align_val_t{CACHE_LINE}));
                if (leaf_chunk0_cap_ > 0) {
                    std::memcpy(mem, leaf_chunks_[0],
                                static_cast<std::size_t>(leaf_chunk0_cap_) * sizeof(LeafNode));
                    ::operator delete(leaf_chunks_[0], std::align_val_t{CACHE_LINE});
                    leaf_chunks_[0] = mem;
                } else {
                    leaf_chunks_.push_back(mem);
                }
                leaf_chunk0_cap_ = new_cap;
            }
        } else if ((id & LEAF_CHUNK_MASK) == 0) [[unlikely]] {
            LeafNode* mem = static_cast<LeafNode*>(
                ::operator new(static_cast<std::size_t>(LEAF_CHUNK_SIZE) * sizeof(LeafNode),
                               std::align_val_t{CACHE_LINE}));
            leaf_chunks_.push_back(mem);
        }
        leaf_count_ = id + 1;
        return id;
    }

    inline void free_leaf(std::uint32_t id) noexcept {
        leaf_at(id).next_free = leaf_free_head_;
        leaf_free_head_ = id;
    }

    std::uint32_t alloc_internal() {
        if (internal_free_head_ != INVALID_ID) {
            std::uint32_t id = internal_free_head_;
            internal_free_head_ = internals_[id].next_free;
            return id;
        }
        std::uint32_t id = internal_count_;
        if (id >= internal_cap_) [[unlikely]] {
            std::uint32_t new_cap = (internal_cap_ == 0) ? 8u : (internal_cap_ * 2u);
            InternalNode* mem = static_cast<InternalNode*>(
                ::operator new(static_cast<std::size_t>(new_cap) * sizeof(InternalNode),
                               std::align_val_t{CACHE_LINE}));
            if (internal_cap_ > 0) {
                std::memcpy(mem, internals_,
                            static_cast<std::size_t>(internal_cap_) * sizeof(InternalNode));
                ::operator delete(internals_, std::align_val_t{CACHE_LINE});
            }
            internals_ = mem;
            internal_cap_ = new_cap;
        }
        internal_count_ = id + 1;
        return id;
    }

    inline void free_internal(std::uint32_t id) noexcept {
        internals_[id].next_free = internal_free_head_;
        internal_free_head_ = id;
    }

    // -------------------------------------------------------- insert (split)

    // Splits full leaf `left_id` (31 keys) + new `(key, value)` at `pos` into
    // left (16 keys) + promoted (1 key) + right (15 keys), then propagates up.
    __attribute__((noinline)) void insert_split_leaf(std::uint32_t left_id,
                                                     std::uint32_t pos,
                                                     std::int64_t key,
                                                     std::int64_t value,
                                                     const PathFrame* path,
                                                     std::uint32_t depth) {
        std::uint32_t right_id = alloc_leaf();
        LeafNode& left = leaf_at(left_id);
        LeafNode& right = leaf_at(right_id);

        std::int64_t promo_key;
        std::int64_t promo_val;

        if (pos > 16) {
            promo_key = left.keys[16];
            promo_val = left.vals[16];
            std::uint32_t before = pos - 17;
            if (before > 0) {
                std::memcpy(right.keys, left.keys + 17,
                            static_cast<std::size_t>(before) * sizeof(std::int64_t));
                std::memcpy(right.vals, left.vals + 17,
                            static_cast<std::size_t>(before) * sizeof(std::int64_t));
            }
            right.keys[before] = key;
            right.vals[before] = value;
            std::uint32_t after = MAX_KEYS - pos;
            if (after > 0) {
                std::memcpy(right.keys + before + 1, left.keys + pos,
                            static_cast<std::size_t>(after) * sizeof(std::int64_t));
                std::memcpy(right.vals + before + 1, left.vals + pos,
                            static_cast<std::size_t>(after) * sizeof(std::int64_t));
            }
        } else if (pos == 16) {
            promo_key = key;
            promo_val = value;
            std::memcpy(right.keys, left.keys + 16, 15 * sizeof(std::int64_t));
            std::memcpy(right.vals, left.vals + 16, 15 * sizeof(std::int64_t));
        } else {
            std::memcpy(right.keys, left.keys + 16, 15 * sizeof(std::int64_t));
            std::memcpy(right.vals, left.vals + 16, 15 * sizeof(std::int64_t));
            promo_key = left.keys[15];
            promo_val = left.vals[15];
            std::uint32_t shift = 15 - pos;
            if (shift > 0) {
                std::memmove(left.keys + pos + 1, left.keys + pos,
                             static_cast<std::size_t>(shift) * sizeof(std::int64_t));
                std::memmove(left.vals + pos + 1, left.vals + pos,
                             static_cast<std::size_t>(shift) * sizeof(std::int64_t));
            }
            left.keys[pos] = key;
            left.vals[pos] = value;
        }

        left.count = 16;
        right.count = 15;
        fill_sentinels(left.keys, 16);
        fill_sentinels(right.keys, 15);

        std::uint32_t promo_child = right_id;

        while (depth > 0) {
            PathFrame frame = path[--depth];
            std::uint32_t pid = frame.id;
            std::uint32_t ppos = frame.pos;
            InternalNode& parent = internals_[pid];
            std::uint32_t pcnt = parent.count;

            if (pcnt < MAX_KEYS) [[likely]] {
                if (ppos < pcnt) {
                    std::size_t nmove = static_cast<std::size_t>(pcnt - ppos);
                    std::memmove(parent.keys + ppos + 1, parent.keys + ppos,
                                 nmove * sizeof(std::int64_t));
                    std::memmove(parent.vals + ppos + 1, parent.vals + ppos,
                                 nmove * sizeof(std::int64_t));
                    std::memmove(parent.children + ppos + 2, parent.children + ppos + 1,
                                 nmove * sizeof(std::uint32_t));
                }
                parent.keys[ppos] = promo_key;
                parent.vals[ppos] = promo_val;
                parent.children[ppos + 1] = promo_child;
                parent.count = pcnt + 1;
                return;
            }

            // Parent internal node is full; split it too.
            std::uint32_t new_right_id = alloc_internal();
            InternalNode& ileft = internals_[pid];
            InternalNode& iright = internals_[new_right_id];

            std::int64_t next_key;
            std::int64_t next_val;

            if (ppos > 16) {
                next_key = ileft.keys[16];
                next_val = ileft.vals[16];
                std::uint32_t before = ppos - 17;
                if (before > 0) {
                    std::memcpy(iright.keys, ileft.keys + 17,
                                static_cast<std::size_t>(before) * sizeof(std::int64_t));
                    std::memcpy(iright.vals, ileft.vals + 17,
                                static_cast<std::size_t>(before) * sizeof(std::int64_t));
                }
                iright.keys[before] = promo_key;
                iright.vals[before] = promo_val;
                std::uint32_t after = MAX_KEYS - ppos;
                if (after > 0) {
                    std::memcpy(iright.keys + before + 1, ileft.keys + ppos,
                                static_cast<std::size_t>(after) * sizeof(std::int64_t));
                    std::memcpy(iright.vals + before + 1, ileft.vals + ppos,
                                static_cast<std::size_t>(after) * sizeof(std::int64_t));
                }
                std::uint32_t cbefore = ppos - 16;
                std::memcpy(iright.children, ileft.children + 17,
                            static_cast<std::size_t>(cbefore) * sizeof(std::uint32_t));
                iright.children[cbefore] = promo_child;
                if (after > 0) {
                    std::memcpy(iright.children + cbefore + 1, ileft.children + ppos + 1,
                                static_cast<std::size_t>(after) * sizeof(std::uint32_t));
                }
            } else if (ppos == 16) {
                next_key = promo_key;
                next_val = promo_val;
                std::memcpy(iright.keys, ileft.keys + 16, 15 * sizeof(std::int64_t));
                std::memcpy(iright.vals, ileft.vals + 16, 15 * sizeof(std::int64_t));
                iright.children[0] = promo_child;
                std::memcpy(iright.children + 1, ileft.children + 17, 15 * sizeof(std::uint32_t));
            } else {
                std::memcpy(iright.keys, ileft.keys + 16, 15 * sizeof(std::int64_t));
                std::memcpy(iright.vals, ileft.vals + 16, 15 * sizeof(std::int64_t));
                std::memcpy(iright.children, ileft.children + 16, 16 * sizeof(std::uint32_t));
                next_key = ileft.keys[15];
                next_val = ileft.vals[15];
                std::uint32_t shift = 15 - ppos;
                if (shift > 0) {
                    std::memmove(ileft.keys + ppos + 1, ileft.keys + ppos,
                                 static_cast<std::size_t>(shift) * sizeof(std::int64_t));
                    std::memmove(ileft.vals + ppos + 1, ileft.vals + ppos,
                                 static_cast<std::size_t>(shift) * sizeof(std::int64_t));
                    std::memmove(ileft.children + ppos + 2, ileft.children + ppos + 1,
                                 static_cast<std::size_t>(shift) * sizeof(std::uint32_t));
                }
                ileft.keys[ppos] = promo_key;
                ileft.vals[ppos] = promo_val;
                ileft.children[ppos + 1] = promo_child;
            }

            ileft.count = 16;
            iright.count = 15;
            fill_sentinels(ileft.keys, 16);
            fill_sentinels(iright.keys, 15);

            promo_key = next_key;
            promo_val = next_val;
            promo_child = new_right_id;
        }

        // Root split: create a new root internal node.
        std::uint32_t new_root_id = alloc_internal();
        InternalNode& nr = internals_[new_root_id];
        nr.keys[0] = promo_key;
        nr.vals[0] = promo_val;
        nr.children[0] = root_;
        nr.children[1] = promo_child;
        nr.count = 1;
        fill_sentinels(nr.keys, 1);
        root_ = new_root_id;
        ++height_;
    }

    // --------------------------------------------------- remove (rebalance)

    static inline void remove_from_parent(InternalNode& parent, std::uint32_t sep_idx) noexcept {
        std::uint32_t pn = parent.count - 1;
        if (sep_idx < pn) {
            std::size_t nmove = static_cast<std::size_t>(pn - sep_idx);
            std::memmove(parent.keys + sep_idx, parent.keys + sep_idx + 1,
                         nmove * sizeof(std::int64_t));
            std::memmove(parent.vals + sep_idx, parent.vals + sep_idx + 1,
                         nmove * sizeof(std::int64_t));
            std::memmove(parent.children + sep_idx + 1, parent.children + sep_idx + 2,
                         nmove * sizeof(std::uint32_t));
        }
        parent.count = pn;
        parent.keys[pn] = SENTINEL;
    }

    __attribute__((noinline)) void rebalance_leaf(std::uint32_t leaf_id,
                                                  const PathFrame* path,
                                                  std::uint32_t depth) noexcept {
        std::uint32_t level_idx = depth - 1;
        std::uint32_t parent_id = path[level_idx].id;
        std::uint32_t ci = path[level_idx].pos;
        InternalNode& parent = internals_[parent_id];
        LeafNode& leaf = leaf_at(leaf_id);

        // Try balanced borrow from right sibling first.
        if (ci < parent.count) {
            std::uint32_t right_id = parent.children[ci + 1];
            LeafNode& right = leaf_at(right_id);
            if (right.count > MIN_KEYS) {
                std::uint32_t nR = right.count;
                std::uint32_t k = (nR - (MIN_KEYS - 2)) >> 1;  // >= 1
                leaf.keys[MIN_KEYS - 1] = parent.keys[ci];
                leaf.vals[MIN_KEYS - 1] = parent.vals[ci];
                if (k > 1) {
                    std::memcpy(leaf.keys + MIN_KEYS, right.keys,
                                static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                    std::memcpy(leaf.vals + MIN_KEYS, right.vals,
                                static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                }
                parent.keys[ci] = right.keys[k - 1];
                parent.vals[ci] = right.vals[k - 1];
                std::uint32_t rem = nR - k;
                std::memmove(right.keys, right.keys + k,
                             static_cast<std::size_t>(rem) * sizeof(std::int64_t));
                std::memmove(right.vals, right.vals + k,
                             static_cast<std::size_t>(rem) * sizeof(std::int64_t));
                fill_sentinels_range(right.keys, rem, nR);
                leaf.count = (MIN_KEYS - 1) + k;
                right.count = rem;
                return;
            }
            // If left sibling can lend, borrow from left; otherwise merge with right.
            if (ci > 0) {
                std::uint32_t left_id = parent.children[ci - 1];
                LeafNode& left = leaf_at(left_id);
                if (left.count > MIN_KEYS) {
                    std::uint32_t nL = left.count;
                    std::uint32_t k = (nL - (MIN_KEYS - 2)) >> 1;  // >= 1
                    std::uint32_t rem = nL - k;
                    std::memmove(leaf.keys + k, leaf.keys,
                                 (MIN_KEYS - 1) * sizeof(std::int64_t));
                    std::memmove(leaf.vals + k, leaf.vals,
                                 (MIN_KEYS - 1) * sizeof(std::int64_t));
                    leaf.keys[k - 1] = parent.keys[ci - 1];
                    leaf.vals[k - 1] = parent.vals[ci - 1];
                    if (k > 1) {
                        std::memcpy(leaf.keys, left.keys + rem + 1,
                                    static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                        std::memcpy(leaf.vals, left.vals + rem + 1,
                                    static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                    }
                    parent.keys[ci - 1] = left.keys[rem];
                    parent.vals[ci - 1] = left.vals[rem];
                    fill_sentinels_range(left.keys, rem, nL);
                    left.count = rem;
                    leaf.count = (MIN_KEYS - 1) + k;
                    return;
                }
            }
            // Merge `leaf` (14) + `parent[ci]` (1) + `right` (15) into `leaf` (30).
            leaf.keys[MIN_KEYS - 1] = parent.keys[ci];
            leaf.vals[MIN_KEYS - 1] = parent.vals[ci];
            std::memcpy(leaf.keys + MIN_KEYS, right.keys, MIN_KEYS * sizeof(std::int64_t));
            std::memcpy(leaf.vals + MIN_KEYS, right.vals, MIN_KEYS * sizeof(std::int64_t));
            leaf.count = 2 * MIN_KEYS;  // 30; keys[30] is already SENTINEL
            free_leaf(right_id);
            remove_from_parent(parent, ci);
        } else {
            // Rightmost child (`ci > 0`): check left sibling.
            std::uint32_t left_id = parent.children[ci - 1];
            LeafNode& left = leaf_at(left_id);
            if (left.count > MIN_KEYS) {
                std::uint32_t nL = left.count;
                std::uint32_t k = (nL - (MIN_KEYS - 2)) >> 1;
                std::uint32_t rem = nL - k;
                std::memmove(leaf.keys + k, leaf.keys, (MIN_KEYS - 1) * sizeof(std::int64_t));
                std::memmove(leaf.vals + k, leaf.vals, (MIN_KEYS - 1) * sizeof(std::int64_t));
                leaf.keys[k - 1] = parent.keys[ci - 1];
                leaf.vals[k - 1] = parent.vals[ci - 1];
                if (k > 1) {
                    std::memcpy(leaf.keys, left.keys + rem + 1,
                                static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                    std::memcpy(leaf.vals, left.vals + rem + 1,
                                static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                }
                parent.keys[ci - 1] = left.keys[rem];
                parent.vals[ci - 1] = left.vals[rem];
                fill_sentinels_range(left.keys, rem, nL);
                left.count = rem;
                leaf.count = (MIN_KEYS - 1) + k;
                return;
            }
            // Merge `left` (15) + `parent[ci - 1]` (1) + `leaf` (14) into `left` (30).
            left.keys[MIN_KEYS] = parent.keys[ci - 1];
            left.vals[MIN_KEYS] = parent.vals[ci - 1];
            std::memcpy(left.keys + MIN_KEYS + 1, leaf.keys,
                        (MIN_KEYS - 1) * sizeof(std::int64_t));
            std::memcpy(left.vals + MIN_KEYS + 1, leaf.vals,
                        (MIN_KEYS - 1) * sizeof(std::int64_t));
            left.count = 2 * MIN_KEYS;  // 30; keys[30] is already SENTINEL
            free_leaf(leaf_id);
            remove_from_parent(parent, ci - 1);
        }

        // Propagate underflow up through internal nodes if needed.
        rebalance_internal_up(level_idx, path);
    }

    void rebalance_internal_up(std::uint32_t level_idx, const PathFrame* path) noexcept {
        while (true) {
            std::uint32_t nid = path[level_idx].id;
            InternalNode& node = internals_[nid];

            if (level_idx == 0) {
                if (node.count == 0) {
                    std::uint32_t new_root = node.children[0];
                    free_internal(nid);
                    root_ = new_root;
                    --height_;
                }
                return;
            }
            if (node.count >= MIN_KEYS) {
                return;
            }

            std::uint32_t parent_idx = level_idx - 1;
            std::uint32_t parent_id = path[parent_idx].id;
            std::uint32_t ci = path[parent_idx].pos;
            InternalNode& parent = internals_[parent_id];

            if (ci < parent.count) {
                std::uint32_t right_id = parent.children[ci + 1];
                InternalNode& right = internals_[right_id];
                if (right.count > MIN_KEYS) {
                    std::uint32_t nR = right.count;
                    std::uint32_t k = (nR - (MIN_KEYS - 2)) >> 1;
                    node.keys[MIN_KEYS - 1] = parent.keys[ci];
                    node.vals[MIN_KEYS - 1] = parent.vals[ci];
                    if (k > 1) {
                        std::memcpy(node.keys + MIN_KEYS, right.keys,
                                    static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                        std::memcpy(node.vals + MIN_KEYS, right.vals,
                                    static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                    }
                    std::memcpy(node.children + MIN_KEYS, right.children,
                                static_cast<std::size_t>(k) * sizeof(std::uint32_t));
                    parent.keys[ci] = right.keys[k - 1];
                    parent.vals[ci] = right.vals[k - 1];
                    std::uint32_t rem = nR - k;
                    std::memmove(right.keys, right.keys + k,
                                 static_cast<std::size_t>(rem) * sizeof(std::int64_t));
                    std::memmove(right.vals, right.vals + k,
                                 static_cast<std::size_t>(rem) * sizeof(std::int64_t));
                    std::memmove(right.children, right.children + k,
                                 static_cast<std::size_t>(rem + 1) * sizeof(std::uint32_t));
                    fill_sentinels_range(right.keys, rem, nR);
                    node.count = (MIN_KEYS - 1) + k;
                    right.count = rem;
                    return;
                }
                if (ci > 0) {
                    std::uint32_t left_id = parent.children[ci - 1];
                    InternalNode& left = internals_[left_id];
                    if (left.count > MIN_KEYS) {
                        std::uint32_t nL = left.count;
                        std::uint32_t k = (nL - (MIN_KEYS - 2)) >> 1;
                        std::uint32_t rem = nL - k;
                        std::memmove(node.keys + k, node.keys,
                                     (MIN_KEYS - 1) * sizeof(std::int64_t));
                        std::memmove(node.vals + k, node.vals,
                                     (MIN_KEYS - 1) * sizeof(std::int64_t));
                        std::memmove(node.children + k, node.children,
                                     MIN_KEYS * sizeof(std::uint32_t));
                        node.keys[k - 1] = parent.keys[ci - 1];
                        node.vals[k - 1] = parent.vals[ci - 1];
                        if (k > 1) {
                            std::memcpy(node.keys, left.keys + rem + 1,
                                        static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                            std::memcpy(node.vals, left.vals + rem + 1,
                                        static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                        }
                        std::memcpy(node.children, left.children + rem + 1,
                                    static_cast<std::size_t>(k) * sizeof(std::uint32_t));
                        parent.keys[ci - 1] = left.keys[rem];
                        parent.vals[ci - 1] = left.vals[rem];
                        fill_sentinels_range(left.keys, rem, nL);
                        left.count = rem;
                        node.count = (MIN_KEYS - 1) + k;
                        return;
                    }
                }
                // Merge `node` (14) + `parent[ci]` (1) + `right` (15) into `node` (30).
                node.keys[MIN_KEYS - 1] = parent.keys[ci];
                node.vals[MIN_KEYS - 1] = parent.vals[ci];
                std::memcpy(node.keys + MIN_KEYS, right.keys, MIN_KEYS * sizeof(std::int64_t));
                std::memcpy(node.vals + MIN_KEYS, right.vals, MIN_KEYS * sizeof(std::int64_t));
                std::memcpy(node.children + MIN_KEYS, right.children,
                            (MIN_KEYS + 1) * sizeof(std::uint32_t));
                node.count = 2 * MIN_KEYS;
                free_internal(right_id);
                remove_from_parent(parent, ci);
            } else {
                std::uint32_t left_id = parent.children[ci - 1];
                InternalNode& left = internals_[left_id];
                if (left.count > MIN_KEYS) {
                    std::uint32_t nL = left.count;
                    std::uint32_t k = (nL - (MIN_KEYS - 2)) >> 1;
                    std::uint32_t rem = nL - k;
                    std::memmove(node.keys + k, node.keys, (MIN_KEYS - 1) * sizeof(std::int64_t));
                    std::memmove(node.vals + k, node.vals, (MIN_KEYS - 1) * sizeof(std::int64_t));
                    std::memmove(node.children + k, node.children,
                                 MIN_KEYS * sizeof(std::uint32_t));
                    node.keys[k - 1] = parent.keys[ci - 1];
                    node.vals[k - 1] = parent.vals[ci - 1];
                    if (k > 1) {
                        std::memcpy(node.keys, left.keys + rem + 1,
                                    static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                        std::memcpy(node.vals, left.vals + rem + 1,
                                    static_cast<std::size_t>(k - 1) * sizeof(std::int64_t));
                    }
                    std::memcpy(node.children, left.children + rem + 1,
                                static_cast<std::size_t>(k) * sizeof(std::uint32_t));
                    parent.keys[ci - 1] = left.keys[rem];
                    parent.vals[ci - 1] = left.vals[rem];
                    fill_sentinels_range(left.keys, rem, nL);
                    left.count = rem;
                    node.count = (MIN_KEYS - 1) + k;
                    return;
                }
                // Merge `left` (15) + `parent[ci - 1]` (1) + `node` (14) into `left` (30).
                left.keys[MIN_KEYS] = parent.keys[ci - 1];
                left.vals[MIN_KEYS] = parent.vals[ci - 1];
                std::memcpy(left.keys + MIN_KEYS + 1, node.keys,
                            (MIN_KEYS - 1) * sizeof(std::int64_t));
                std::memcpy(left.vals + MIN_KEYS + 1, node.vals,
                            (MIN_KEYS - 1) * sizeof(std::int64_t));
                std::memcpy(left.children + MIN_KEYS + 1, node.children,
                            MIN_KEYS * sizeof(std::uint32_t));
                left.count = 2 * MIN_KEYS;
                free_internal(nid);
                remove_from_parent(parent, ci - 1);
            }

            level_idx = parent_idx;
        }
    }

    // --------------------------------------------------------- range helpers

    static inline bool emit_leaf_full(const LeafNode& leaf, std::int64_t hi,
                                      std::int64_t* out_keys, std::int64_t* out_vals,
                                      std::size_t limit, std::size_t& written) noexcept {
        std::uint32_t cnt = leaf.count;
        std::size_t rem = limit - written;
        if (cnt <= rem && leaf.keys[cnt - 1] <= hi) [[likely]] {
            std::memcpy(out_keys + written, leaf.keys,
                        static_cast<std::size_t>(cnt) * sizeof(std::int64_t));
            std::memcpy(out_vals + written, leaf.vals,
                        static_cast<std::size_t>(cnt) * sizeof(std::int64_t));
            written += cnt;
            return (written == limit) || (leaf.keys[cnt - 1] == hi);
        }
        std::uint32_t max_take = (cnt < rem) ? cnt : static_cast<std::uint32_t>(rem);
        for (std::uint32_t i = 0; i < max_take && leaf.keys[i] <= hi; ++i) {
            out_keys[written] = leaf.keys[i];
            out_vals[written] = leaf.vals[i];
            ++written;
        }
        return true;
    }

    static inline bool emit_leaf_from(const LeafNode& leaf, std::int64_t lo, std::int64_t hi,
                                      std::int64_t* out_keys, std::int64_t* out_vals,
                                      std::size_t limit, std::size_t& written) noexcept {
        std::uint32_t cnt = leaf.count;
        std::uint32_t pos = search_keys(leaf.keys, lo);
        if (pos >= cnt) {
            return false;
        }
        std::uint32_t avail = cnt - pos;
        std::size_t rem = limit - written;
        if (avail <= rem && leaf.keys[cnt - 1] <= hi) {
            std::memcpy(out_keys + written, leaf.keys + pos,
                        static_cast<std::size_t>(avail) * sizeof(std::int64_t));
            std::memcpy(out_vals + written, leaf.vals + pos,
                        static_cast<std::size_t>(avail) * sizeof(std::int64_t));
            written += avail;
            return (written == limit) || (leaf.keys[cnt - 1] == hi);
        }
        std::uint32_t max_take = (avail < rem) ? avail : static_cast<std::uint32_t>(rem);
        for (std::uint32_t i = 0; i < max_take && leaf.keys[pos + i] <= hi; ++i) {
            out_keys[written] = leaf.keys[pos + i];
            out_vals[written] = leaf.vals[pos + i];
            ++written;
        }
        return true;
    }

    bool range_continue(std::uint32_t id, std::uint32_t level, std::int64_t hi,
                        std::int64_t* out_keys, std::int64_t* out_vals,
                        std::size_t limit, std::size_t& written) const noexcept {
        const InternalNode& node = internals_[id];
        std::uint32_t cnt = node.count;
        if (level == 1) {
            std::size_t rem_est = limit - written;
            std::uint32_t pf_dist = (rem_est >= 64) ? 4u
                                                    : static_cast<std::uint32_t>((rem_est >> 4) + 1u);
            std::uint32_t pf_init = (pf_dist < cnt) ? pf_dist : cnt;
            for (std::uint32_t p = 0; p <= pf_init; ++p) {
                prefetch_leaf(&leaf_at(node.children[p]));
            }
            for (std::uint32_t i = 0;; ++i) {
                if (i + pf_dist + 1 <= cnt) {
                    prefetch_leaf(&leaf_at(node.children[i + pf_dist + 1]));
                }
                if (emit_leaf_full(leaf_at(node.children[i]), hi,
                                   out_keys, out_vals, limit, written)) {
                    return true;
                }
                if (i == cnt) {
                    return false;
                }
                std::int64_t k = node.keys[i];
                if (k > hi) {
                    return true;
                }
                out_keys[written] = k;
                out_vals[written] = node.vals[i];
                ++written;
                if (written == limit || k == hi) {
                    return true;
                }
            }
        }
        for (std::uint32_t i = 0;; ++i) {
            if (i + 1 <= cnt) {
                prefetch_internal(&internals_[node.children[i + 1]]);
            }
            if (range_continue(node.children[i], level - 1, hi,
                               out_keys, out_vals, limit, written)) {
                return true;
            }
            if (i == cnt) {
                return false;
            }
            std::int64_t k = node.keys[i];
            if (k > hi) {
                return true;
            }
            out_keys[written] = k;
            out_vals[written] = node.vals[i];
            ++written;
            if (written == limit || k == hi) {
                return true;
            }
        }
    }

    bool range_start(std::uint32_t id, std::uint32_t level,
                     std::int64_t lo, std::int64_t hi,
                     std::int64_t* out_keys, std::int64_t* out_vals,
                     std::size_t limit, std::size_t& written) const noexcept {
        const InternalNode& node = internals_[id];
        std::uint32_t cnt = node.count;
        std::uint32_t pos = search_keys(node.keys, lo);
        std::uint32_t safe_pos = (pos < MAX_KEYS) ? pos : 0u;
        std::uint32_t i = pos;

        if ((pos < cnt) & (node.keys[safe_pos] == lo)) {
            out_keys[written] = node.keys[pos];
            out_vals[written] = node.vals[pos];
            ++written;
            if (written == limit || lo == hi) {
                return true;
            }
            i = pos + 1;
        } else {
            if (level == 1) {
                if (pos + 1 <= cnt) {
                    prefetch_leaf(&leaf_at(node.children[pos + 1]));
                }
                if (emit_leaf_from(leaf_at(node.children[pos]), lo, hi,
                                   out_keys, out_vals, limit, written)) {
                    return true;
                }
            } else {
                if (range_start(node.children[pos], level - 1, lo, hi,
                                out_keys, out_vals, limit, written)) {
                    return true;
                }
            }
            if (pos == cnt) {
                return false;
            }
            std::int64_t k = node.keys[pos];
            if (k > hi) {
                return true;
            }
            out_keys[written] = k;
            out_vals[written] = node.vals[pos];
            ++written;
            if (written == limit || k == hi) {
                return true;
            }
            i = pos + 1;
        }

        if (level == 1) {
            std::size_t rem_est = limit - written;
            std::uint32_t pf_dist = (rem_est >= 64) ? 4u
                                                    : static_cast<std::uint32_t>((rem_est >> 4) + 1u);
            std::uint32_t pf_end = (i + pf_dist < cnt) ? (i + pf_dist) : cnt;
            for (std::uint32_t p = i; p <= pf_end; ++p) {
                prefetch_leaf(&leaf_at(node.children[p]));
            }
            for (;; ++i) {
                if (i + pf_dist + 1 <= cnt) {
                    prefetch_leaf(&leaf_at(node.children[i + pf_dist + 1]));
                }
                if (emit_leaf_full(leaf_at(node.children[i]), hi,
                                   out_keys, out_vals, limit, written)) {
                    return true;
                }
                if (i == cnt) {
                    return false;
                }
                std::int64_t k = node.keys[i];
                if (k > hi) {
                    return true;
                }
                out_keys[written] = k;
                out_vals[written] = node.vals[i];
                ++written;
                if (written == limit || k == hi) {
                    return true;
                }
            }
        }

        for (;; ++i) {
            if (i + 1 <= cnt) {
                prefetch_internal(&internals_[node.children[i + 1]]);
            }
            if (range_continue(node.children[i], level - 1, hi,
                               out_keys, out_vals, limit, written)) {
                return true;
            }
            if (i == cnt) {
                return false;
            }
            std::int64_t k = node.keys[i];
            if (k > hi) {
                return true;
            }
            out_keys[written] = k;
            out_vals[written] = node.vals[i];
            ++written;
            if (written == limit || k == hi) {
                return true;
            }
        }
    }

    // -------------------------------------------------------------- members

    InternalNode* internals_ = nullptr;
    std::vector<LeafNode*> leaf_chunks_;
    std::size_t len_ = 0;
    std::uint32_t root_ = INVALID_ID;
    std::uint32_t height_ = 0;
    std::uint32_t internal_count_ = 0;
    std::uint32_t internal_cap_ = 0;
    std::uint32_t internal_free_head_ = INVALID_ID;
    std::uint32_t leaf_count_ = 0;
    std::uint32_t leaf_chunk0_cap_ = 0;
    std::uint32_t leaf_free_head_ = INVALID_ID;
};
