// Classic in-memory B-tree (Bayer & McCreight / CLRS) with minimum degree t = 16.
// Entries (Int64 -> Int64) live in both internal nodes and leaves.

final class BTree {
    // Compile-time constants for minimum degree t = 16.
    // Max keys = 2t - 1 = 31, min keys (non-root) = t - 1 = 15, max children = 2t = 32.
    private static let MIN_KEYS = 15
    private static let MAX_KEYS = 31
    private static let NULL_NODE: UInt32 = 0xFFFF_FFFF

    // Leaf node layout (512 bytes = 4 x 128-byte cache lines, 128-byte aligned):
    //   [0..3]     count: Int32 (or freelist next: UInt32 when freed)
    //   [4..7]     padding
    //   [8..127]   keys[0..14]  (Cache Line 0: header + first 15 keys)
    //   [128..255] keys[15..30] (Cache Line 1: remaining 16 keys)
    //   [256..503] vals[0..30]  (Cache Lines 2-3: 31 values)
    //   [504..511] padding
    private static let LEAF_STRIDE = 512
    private static let LEAF_SHIFT = 9
    private static let KEYS_OFFSET = 8
    private static let LEAF_VALS_OFFSET = 256

    // Internal node hot layout (384 bytes = 3 x 128-byte cache lines, 128-byte aligned):
    //   [0..3]     count: Int32 (or freelist next: UInt32 when freed)
    //   [4..7]     padding
    //   [8..127]   keys[0..14]      (Cache Line 0)
    //   [128..255] keys[15..30]     (Cache Line 1)
    //   [256..383] children[0..31]  (Cache Line 2: 32 x UInt32 indices)
    // Internal node values live in a parallel pool (256 bytes = 32 x Int64 per node)
    // so tree descent touches only the 384-byte hot region (fits in L2 cache at 4M entries).
    private static let INT_HOT_STRIDE = 384
    private static let INT_CHILDREN_OFFSET = 256
    private static let INT_VAL_SHIFT = 5  // 32 Int64s = 256 bytes per internal node

    // Tree state
    private var root: UInt32 = NULL_NODE
    private var _height: Int = 0
    private var _count: Int = 0

    // Leaf pool (128-byte aligned contiguous buffer + intrusive O(1) freelist)
    private var leafBuf: UnsafeMutableRawPointer? = nil
    private var leafCap: Int = 0
    private var leafBump: Int = 0
    private var leafFreeHead: UInt32 = NULL_NODE

    // Internal node pools (hot keys+children + parallel values + intrusive O(1) freelist)
    private var intHotBuf: UnsafeMutableRawPointer? = nil
    private var intValBuf: UnsafeMutablePointer<Int64>? = nil
    private var intCap: Int = 0
    private var intBump: Int = 0
    private var intFreeHead: UInt32 = NULL_NODE

    // Reusable 16-entry path stack (allocated lazily when tree reaches height >= 2)
    // Eliminates per-call stack zero-initialization overhead in insert/remove/range.
    private var pathBuf: UnsafeMutablePointer<UInt64>? = nil

    init() {}

    deinit {
        leafBuf?.deallocate()
        intHotBuf?.deallocate()
        if let v = intValBuf {
            UnsafeMutableRawPointer(v).deallocate()
        }
        if let pb = pathBuf {
            UnsafeMutableRawPointer(pb).deallocate()
        }
    }

    var count: Int {
        @inline(__always) get { _count }
    }

    @inline(__always)
    func height() -> Int {
        _height
    }

    // ------------------------------------------------------------------ Pool Helpers

    @inline(__always)
    private func leafPtr(_ idx: Int) -> UnsafeMutableRawPointer {
        leafBuf.unsafelyUnwrapped.advanced(by: idx &<< Self.LEAF_SHIFT)
    }

    @inline(__always)
    private func leafCount(_ p: UnsafeMutableRawPointer) -> Int {
        Int(p.load(as: Int32.self))
    }

    @inline(__always)
    private func setLeafCount(_ p: UnsafeMutableRawPointer, _ c: Int) {
        p.storeBytes(of: Int32(truncatingIfNeeded: c), as: Int32.self)
    }

    @inline(__always)
    private func leafKeys(_ p: UnsafeMutableRawPointer) -> UnsafeMutablePointer<Int64> {
        p.advanced(by: Self.KEYS_OFFSET).assumingMemoryBound(to: Int64.self)
    }

    @inline(__always)
    private func leafVals(_ p: UnsafeMutableRawPointer) -> UnsafeMutablePointer<Int64> {
        p.advanced(by: Self.LEAF_VALS_OFFSET).assumingMemoryBound(to: Int64.self)
    }

    @inline(__always)
    private func intHotPtr(_ idx: Int) -> UnsafeMutableRawPointer {
        intHotBuf.unsafelyUnwrapped.advanced(by: idx &* Self.INT_HOT_STRIDE)
    }

    @inline(__always)
    private func intCount(_ p: UnsafeMutableRawPointer) -> Int {
        Int(p.load(as: Int32.self))
    }

    @inline(__always)
    private func setIntCount(_ p: UnsafeMutableRawPointer, _ c: Int) {
        p.storeBytes(of: Int32(truncatingIfNeeded: c), as: Int32.self)
    }

    @inline(__always)
    private func intKeys(_ p: UnsafeMutableRawPointer) -> UnsafeMutablePointer<Int64> {
        p.advanced(by: Self.KEYS_OFFSET).assumingMemoryBound(to: Int64.self)
    }

    @inline(__always)
    private func intChildren(_ p: UnsafeMutableRawPointer) -> UnsafeMutablePointer<UInt32> {
        p.advanced(by: Self.INT_CHILDREN_OFFSET).assumingMemoryBound(to: UInt32.self)
    }

    @inline(__always)
    private func intVals(_ idx: Int) -> UnsafeMutablePointer<Int64> {
        intValBuf.unsafelyUnwrapped.advanced(by: idx &<< Self.INT_VAL_SHIFT)
    }

    @inline(never)
    private func growLeaves() {
        let newCap = leafCap == 0 ? 16 : (leafCap &<< 1)
        let newBuf = UnsafeMutableRawPointer.allocate(byteCount: newCap &* Self.LEAF_STRIDE, alignment: 128)
        if let old = leafBuf {
            if leafBump > 0 {
                newBuf.copyMemory(from: old, byteCount: leafBump &* Self.LEAF_STRIDE)
            }
            old.deallocate()
        }
        leafBuf = newBuf
        leafCap = newCap
    }

    @inline(__always)
    private func allocLeaf() -> UInt32 {
        let head = leafFreeHead
        if head != Self.NULL_NODE {
            let p = leafPtr(Int(head))
            leafFreeHead = p.load(as: UInt32.self)
            return head
        }
        if leafBump == leafCap {
            growLeaves()
        }
        let idx = UInt32(truncatingIfNeeded: leafBump)
        leafBump &+= 1
        return idx
    }

    @inline(__always)
    private func freeLeaf(_ idx: UInt32) {
        let p = leafPtr(Int(idx))
        p.storeBytes(of: leafFreeHead, as: UInt32.self)
        leafFreeHead = idx
    }

    @inline(never)
    private func growInternals() {
        let newCap = intCap == 0 ? 8 : (intCap &<< 1)
        let newHot = UnsafeMutableRawPointer.allocate(byteCount: newCap &* Self.INT_HOT_STRIDE, alignment: 128)
        let newValRaw = UnsafeMutableRawPointer.allocate(byteCount: newCap &* 256, alignment: 128)
        if let oldHot = intHotBuf {
            if intBump > 0 {
                newHot.copyMemory(from: oldHot, byteCount: intBump &* Self.INT_HOT_STRIDE)
                newValRaw.copyMemory(from: UnsafeMutableRawPointer(intValBuf.unsafelyUnwrapped),
                                     byteCount: intBump &* 256)
            }
            oldHot.deallocate()
            UnsafeMutableRawPointer(intValBuf.unsafelyUnwrapped).deallocate()
        }
        intHotBuf = newHot
        intValBuf = newValRaw.assumingMemoryBound(to: Int64.self)
        intCap = newCap
        if pathBuf == nil {
            pathBuf = UnsafeMutableRawPointer.allocate(byteCount: 16 &* 8, alignment: 128)
                .assumingMemoryBound(to: UInt64.self)
        }
    }

    @inline(__always)
    private func allocInternal() -> UInt32 {
        let head = intFreeHead
        if head != Self.NULL_NODE {
            let p = intHotPtr(Int(head))
            intFreeHead = p.load(as: UInt32.self)
            return head
        }
        if intBump == intCap {
            growInternals()
        }
        let idx = UInt32(truncatingIfNeeded: intBump)
        intBump &+= 1
        return idx
    }

    @inline(__always)
    private func freeInternal(_ idx: UInt32) {
        let p = intHotPtr(Int(idx))
        p.storeBytes(of: intFreeHead, as: UInt32.self)
        intFreeHead = idx
    }

    // ------------------------------------------------------------------ In-Node Search

    // Branchless lower_bound for 15 <= n <= 31 using a single branchless pivot into
    // a 15-key window, followed by portable SIMD4/SIMD2 comparison and sum.
    // Touches only Cache Line 0 whenever keys[probe] >= target (~50%+ of lookups, 100% when n == 15).
    @inline(__always)
    private static func lowerBound15(_ keys: UnsafePointer<Int64>, _ n: Int, _ target: Int64) -> Int {
        let probe = n > 15 ? (n &- 16) : 0
        let rem = n &- 15
        let base = keys[probe] < target ? rem : 0

        let raw = UnsafeRawPointer(keys.advanced(by: base))
        let t4 = SIMD4<Int64>(repeating: target)
        let neg1_4 = SIMD4<Int64>(repeating: -1)
        let z4 = SIMD4<Int64>.zero

        let v0 = raw.loadUnaligned(as: SIMD4<Int64>.self)
        let v1 = raw.loadUnaligned(fromByteOffset: 32, as: SIMD4<Int64>.self)
        let v2 = raw.loadUnaligned(fromByteOffset: 64, as: SIMD4<Int64>.self)
        let v3 = raw.loadUnaligned(fromByteOffset: 96, as: SIMD2<Int64>.self)
        let s14 = keys[base &+ 14]

        let m0 = z4.replacing(with: neg1_4, where: v0 .< t4)
        let m1 = z4.replacing(with: neg1_4, where: v1 .< t4)
        let m2 = z4.replacing(with: neg1_4, where: v2 .< t4)
        let m3 = SIMD2<Int64>.zero.replacing(
            with: neg1_4.lowHalf,
            where: v3 .< t4.lowHalf
        )

        // Balanced depth-3 NEON reduction tree
        let s01 = (m0.lowHalf &+ m0.highHalf) &+ (m1.lowHalf &+ m1.highHalf)
        let s23 = (m2.lowHalf &+ m2.highHalf) &+ m3
        let sum2 = s01 &+ s23
        let countLT = Int(0 &- (sum2[0] &+ sum2[1])) &+ (s14 < target ? 1 : 0)
        return base &+ countLT
    }

    // Branchless lower_bound for 1 <= n <= 14 (only needed at the root).
    @inline(__always)
    private static func lowerBoundSmall(_ keys: UnsafePointer<Int64>, _ n: Int, _ target: Int64) -> Int {
        var base = 0
        var len = n
        while len > 1 {
            let half = len &>> 1
            base &+= keys[base &+ half &- 1] < target ? half : 0
            len &-= half
        }
        base &+= keys[base] < target ? 1 : 0
        return base
    }

    @inline(__always)
    private static func lowerBoundRoot(_ keys: UnsafePointer<Int64>, _ n: Int, _ target: Int64) -> Int {
        if n >= 15 {
            return lowerBound15(keys, n, target)
        }
        return lowerBoundSmall(keys, n, target)
    }

    // ------------------------------------------------------------------ Inline Copy/Shift Helpers

    @inline(__always)
    private static func shiftRight64(_ p: UnsafeMutablePointer<Int64>, _ from: Int, _ count: Int) {
        var i = count
        while i > from {
            p[i] = p[i &- 1]
            i &-= 1
        }
    }

    @inline(__always)
    private static func shiftLeft64(_ p: UnsafeMutablePointer<Int64>, _ from: Int, _ count: Int) {
        var i = from
        let end = count &- 1
        while i < end {
            p[i] = p[i &+ 1]
            i &+= 1
        }
    }

    @inline(__always)
    private static func shiftRight32(_ p: UnsafeMutablePointer<UInt32>, _ from: Int, _ count: Int) {
        var i = count
        while i > from {
            p[i] = p[i &- 1]
            i &-= 1
        }
    }

    @inline(__always)
    private static func shiftLeft32(_ p: UnsafeMutablePointer<UInt32>, _ from: Int, _ count: Int) {
        var i = from
        let end = count &- 1
        while i < end {
            p[i] = p[i &+ 1]
            i &+= 1
        }
    }

    @inline(__always)
    private static func copy64(_ dst: UnsafeMutablePointer<Int64>, _ src: UnsafePointer<Int64>, _ n: Int) {
        var i = 0
        while i &+ 4 <= n {
            let a = src[i]
            let b = src[i &+ 1]
            let c = src[i &+ 2]
            let d = src[i &+ 3]
            dst[i] = a
            dst[i &+ 1] = b
            dst[i &+ 2] = c
            dst[i &+ 3] = d
            i &+= 4
        }
        while i < n {
            dst[i] = src[i]
            i &+= 1
        }
    }

    @inline(__always)
    private static func copy32(_ dst: UnsafeMutablePointer<UInt32>, _ src: UnsafePointer<UInt32>, _ n: Int) {
        var i = 0
        while i &+ 4 <= n {
            let a = src[i]
            let b = src[i &+ 1]
            let c = src[i &+ 2]
            let d = src[i &+ 3]
            dst[i] = a
            dst[i &+ 1] = b
            dst[i &+ 2] = c
            dst[i &+ 3] = d
            i &+= 4
        }
        while i < n {
            dst[i] = src[i]
            i &+= 1
        }
    }

    // Shift p[0..<n] right by `by` slots (overlapping, backward).
    @inline(__always)
    private static func shiftRightBy64(_ p: UnsafeMutablePointer<Int64>, _ n: Int, _ by: Int) {
        var i = n &- 1
        while i >= 0 {
            p[i &+ by] = p[i]
            i &-= 1
        }
    }

    @inline(__always)
    private static func shiftRightBy32(_ p: UnsafeMutablePointer<UInt32>, _ n: Int, _ by: Int) {
        var i = n &- 1
        while i >= 0 {
            p[i &+ by] = p[i]
            i &-= 1
        }
    }

    // Shift p[by..<n] left by `by` slots (overlapping, forward).
    @inline(__always)
    private static func shiftLeftBy64(_ p: UnsafeMutablePointer<Int64>, _ n: Int, _ by: Int) {
        let len = n &- by
        var i = 0
        while i < len {
            p[i] = p[i &+ by]
            i &+= 1
        }
    }

    @inline(__always)
    private static func shiftLeftBy32(_ p: UnsafeMutablePointer<UInt32>, _ n: Int, _ by: Int) {
        let len = n &- by
        var i = 0
        while i < len {
            p[i] = p[i &+ by]
            i &+= 1
        }
    }

    // ------------------------------------------------------------------ get

    func get(_ key: Int64) -> Int64? {
        let h = _height
        if h == 0 { return nil }

        var idx = Int(root)
        if h == 1 {
            let lp = leafPtr(idx)
            let cnt = leafCount(lp)
            let ks = leafKeys(lp)
            let pos = Self.lowerBoundRoot(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                return leafVals(lp)[pos]
            }
            return nil
        }

        // Level 0 (root internal node: may have < 15 keys)
        var rem = h &- 1
        do {
            let hp = intHotPtr(idx)
            let cnt = intCount(hp)
            let ks = intKeys(hp)
            let pos = Self.lowerBoundRoot(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                return intVals(idx)[pos]
            }
            idx = Int(intChildren(hp)[pos])
            rem &-= 1
        }

        // Remaining internal levels (guaranteed count >= 15)
        while rem > 0 {
            let hp = intHotPtr(idx)
            let cnt = intCount(hp)
            let ks = intKeys(hp)
            let pos = Self.lowerBound15(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                return intVals(idx)[pos]
            }
            idx = Int(intChildren(hp)[pos])
            rem &-= 1
        }

        // Leaf level (non-root: guaranteed count >= 15)
        let lp = leafPtr(idx)
        let cnt = leafCount(lp)
        let ks = leafKeys(lp)
        let pos = Self.lowerBound15(ks, cnt, key)
        if pos < cnt && ks[pos] == key {
            return leafVals(lp)[pos]
        }
        return nil
    }

    // ------------------------------------------------------------------ insert

    @inline(__always)
    private static func packFrame(_ nodeIdx: Int, _ pos: Int) -> UInt64 {
        UInt64(UInt32(truncatingIfNeeded: nodeIdx)) | (UInt64(UInt32(truncatingIfNeeded: pos)) &<< 32)
    }

    func insert(_ key: Int64, _ value: Int64) -> Bool {
        let h = _height
        if h == 0 {
            let r = allocLeaf()
            let lp = leafPtr(Int(r))
            setLeafCount(lp, 1)
            leafKeys(lp)[0] = key
            leafVals(lp)[0] = value
            root = r
            _height = 1
            _count = 1
            return true
        }

        if h == 1 {
            let idx = Int(root)
            let lp = leafPtr(idx)
            let cnt = leafCount(lp)
            let ks = leafKeys(lp)
            let pos = Self.lowerBoundRoot(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                leafVals(lp)[pos] = value
                return false
            }
            if cnt < Self.MAX_KEYS {
                let vs = leafVals(lp)
                Self.shiftRight64(ks, pos, cnt)
                Self.shiftRight64(vs, pos, cnt)
                ks[pos] = key
                vs[pos] = value
                setLeafCount(lp, cnt &+ 1)
                _count &+= 1
                return true
            }
            return splitLeafAndPropagate(idx, pos, key, value, 0)
        }

        // Height >= 2: optimistic read-only descent recording path in reusable pathBuf
        let stack = pathBuf.unsafelyUnwrapped
        var idx = Int(root)
        var sp = 0
        var rem = h &- 1

        // Level 0 (root internal)
        do {
            let hp = intHotPtr(idx)
            let cnt = intCount(hp)
            let ks = intKeys(hp)
            let pos = Self.lowerBoundRoot(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                intVals(idx)[pos] = value
                return false
            }
            stack[0] = Self.packFrame(idx, pos)
            sp = 1
            idx = Int(intChildren(hp)[pos])
            rem &-= 1
        }

        // Remaining internal levels
        while rem > 0 {
            let hp = intHotPtr(idx)
            let cnt = intCount(hp)
            let ks = intKeys(hp)
            let pos = Self.lowerBound15(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                intVals(idx)[pos] = value
                return false
            }
            stack[sp] = Self.packFrame(idx, pos)
            sp &+= 1
            idx = Int(intChildren(hp)[pos])
            rem &-= 1
        }

        // Leaf level
        let lp = leafPtr(idx)
        let cnt = leafCount(lp)
        let ks = leafKeys(lp)
        let pos = Self.lowerBound15(ks, cnt, key)
        if pos < cnt && ks[pos] == key {
            leafVals(lp)[pos] = value
            return false
        }

        if cnt < Self.MAX_KEYS {
            let vs = leafVals(lp)
            Self.shiftRight64(ks, pos, cnt)
            Self.shiftRight64(vs, pos, cnt)
            ks[pos] = key
            vs[pos] = value
            setLeafCount(lp, cnt &+ 1)
            _count &+= 1
            return true
        }

        return splitLeafAndPropagate(idx, pos, key, value, sp)
    }

    // Cold path: split full 31-key leaf (into 16 left + 1 promoted + 15 right)
    // and propagate splits upward as needed.
    @inline(never)
    private func splitLeafAndPropagate(
        _ leafIdx: Int,
        _ pos: Int,
        _ key: Int64,
        _ value: Int64,
        _ depth: Int
    ) -> Bool {
        // Allocate right leaf BEFORE taking any raw pointers into leafBuf!
        let rightLeafU32 = allocLeaf()
        let rightLeafIdx = Int(rightLeafU32)

        let lp = leafPtr(leafIdx)
        let rp = leafPtr(rightLeafIdx)
        let lks = leafKeys(lp)
        let lvs = leafVals(lp)
        let rks = leafKeys(rp)
        let rvs = leafVals(rp)

        var promKey: Int64
        var promVal: Int64

        if pos < 16 {
            // Left gets old[0..<pos], new, old[pos..<15] (16 keys); promoted = old[15]; right = old[16..<31] (15 keys)
            promKey = lks[15]
            promVal = lvs[15]
            Self.copy64(rks, lks.advanced(by: 16), 15)
            Self.copy64(rvs, lvs.advanced(by: 16), 15)
            Self.shiftRight64(lks, pos, 15)
            Self.shiftRight64(lvs, pos, 15)
            lks[pos] = key
            lvs[pos] = value
        } else if pos == 16 {
            // Left keeps old[0..<16] (16 keys); promoted = new; right = old[16..<31] (15 keys)
            promKey = key
            promVal = value
            Self.copy64(rks, lks.advanced(by: 16), 15)
            Self.copy64(rvs, lvs.advanced(by: 16), 15)
        } else {
            // pos > 16: left keeps old[0..<16] (16 keys); promoted = old[16];
            // right gets old[17..<pos], new, old[pos..<31] (15 keys)
            promKey = lks[16]
            promVal = lvs[16]
            let before = pos &- 17
            if before > 0 {
                Self.copy64(rks, lks.advanced(by: 17), before)
                Self.copy64(rvs, lvs.advanced(by: 17), before)
            }
            rks[before] = key
            rvs[before] = value
            let after = 31 &- pos
            if after > 0 {
                Self.copy64(rks.advanced(by: before &+ 1), lks.advanced(by: pos), after)
                Self.copy64(rvs.advanced(by: before &+ 1), lvs.advanced(by: pos), after)
            }
        }

        setLeafCount(lp, 16)
        setLeafCount(rp, 15)

        var newChild = rightLeafU32
        var sp = depth

        // Propagate up through internal parents
        if sp > 0 {
            let stack = pathBuf.unsafelyUnwrapped
            while sp > 0 {
                sp &-= 1
                let frame = stack[sp]
            let pIdx = Int(frame & 0xFFFF_FFFF)
            let pPos = Int(frame &>> 32)

            let hp = intHotPtr(pIdx)
            let pCnt = intCount(hp)

            if pCnt < Self.MAX_KEYS {
                let pks = intKeys(hp)
                let pvs = intVals(pIdx)
                let pcs = intChildren(hp)
                Self.shiftRight64(pks, pPos, pCnt)
                Self.shiftRight64(pvs, pPos, pCnt)
                Self.shiftRight32(pcs, pPos &+ 1, pCnt &+ 1)
                pks[pPos] = promKey
                pvs[pPos] = promVal
                pcs[pPos &+ 1] = newChild
                setIntCount(hp, pCnt &+ 1)
                _count &+= 1
                return true
            }

            // Parent internal node is full (31 keys): split into 16 left + 1 promoted + 15 right
            let rightIntU32 = allocInternal()
            let rightIntIdx = Int(rightIntU32)

            // Recompute pointers after allocInternal()!
            let lhp = intHotPtr(pIdx)
            let rhp = intHotPtr(rightIntIdx)
            let lks = intKeys(lhp)
            let lvs = intVals(pIdx)
            let lcs = intChildren(lhp)
            let rks = intKeys(rhp)
            let rvs = intVals(rightIntIdx)
            let rcs = intChildren(rhp)

            let insKey = promKey
            let insVal = promVal
            let insChild = newChild

            if pPos < 16 {
                promKey = lks[15]
                promVal = lvs[15]
                Self.copy64(rks, lks.advanced(by: 16), 15)
                Self.copy64(rvs, lvs.advanced(by: 16), 15)
                Self.copy32(rcs, lcs.advanced(by: 16), 16)

                Self.shiftRight64(lks, pPos, 15)
                Self.shiftRight64(lvs, pPos, 15)
                Self.shiftRight32(lcs, pPos &+ 1, 16)
                lks[pPos] = insKey
                lvs[pPos] = insVal
                lcs[pPos &+ 1] = insChild
            } else if pPos == 16 {
                promKey = insKey
                promVal = insVal
                Self.copy64(rks, lks.advanced(by: 16), 15)
                Self.copy64(rvs, lvs.advanced(by: 16), 15)
                rcs[0] = insChild
                Self.copy32(rcs.advanced(by: 1), lcs.advanced(by: 17), 15)
            } else {
                promKey = lks[16]
                promVal = lvs[16]
                let before = pPos &- 17
                if before > 0 {
                    Self.copy64(rks, lks.advanced(by: 17), before)
                    Self.copy64(rvs, lvs.advanced(by: 17), before)
                }
                rks[before] = insKey
                rvs[before] = insVal
                let after = 31 &- pPos
                if after > 0 {
                    Self.copy64(rks.advanced(by: before &+ 1), lks.advanced(by: pPos), after)
                    Self.copy64(rvs.advanced(by: before &+ 1), lvs.advanced(by: pPos), after)
                }
                let cBefore = pPos &- 16
                Self.copy32(rcs, lcs.advanced(by: 17), cBefore)
                rcs[cBefore] = insChild
                let cAfter = 31 &- pPos
                if cAfter > 0 {
                    Self.copy32(rcs.advanced(by: cBefore &+ 1), lcs.advanced(by: pPos &+ 1), cAfter)
                }
            }

            setIntCount(lhp, 16)
            setIntCount(rhp, 15)
            newChild = rightIntU32
            }
        }

        // Root was split: create new root internal node
        let newRootU32 = allocInternal()
        let newRootIdx = Int(newRootU32)
        let rhp = intHotPtr(newRootIdx)
        setIntCount(rhp, 1)
        intKeys(rhp)[0] = promKey
        intVals(newRootIdx)[0] = promVal
        let rcs = intChildren(rhp)
        rcs[0] = root
        rcs[1] = newChild
        root = newRootU32
        _height &+= 1
        _count &+= 1
        return true
    }

    // ------------------------------------------------------------------ remove

    func remove(_ key: Int64) -> Bool {
        let h = _height
        if h == 0 { return false }

        if h == 1 {
            let idx = Int(root)
            let lp = leafPtr(idx)
            let cnt = leafCount(lp)
            let ks = leafKeys(lp)
            let pos = Self.lowerBoundRoot(ks, cnt, key)
            if pos >= cnt || ks[pos] != key {
                return false
            }
            let vs = leafVals(lp)
            Self.shiftLeft64(ks, pos, cnt)
            Self.shiftLeft64(vs, pos, cnt)
            let newCnt = cnt &- 1
            _count &-= 1
            if newCnt == 0 {
                freeLeaf(root)
                root = Self.NULL_NODE
                _height = 0
            } else {
                setLeafCount(lp, newCnt)
            }
            return true
        }

        let stack = pathBuf.unsafelyUnwrapped
        var idx = Int(root)
        var sp = 0
        var rem = h &- 1

        // Level 0 (root internal)
        do {
            let hp = intHotPtr(idx)
            let cnt = intCount(hp)
            let ks = intKeys(hp)
            let pos = Self.lowerBoundRoot(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                return removeFromInternal(idx, pos, rem, 0)
            }
            stack[0] = Self.packFrame(idx, pos)
            sp = 1
            idx = Int(intChildren(hp)[pos])
            rem &-= 1
        }

        // Remaining internal levels
        while rem > 0 {
            let hp = intHotPtr(idx)
            let cnt = intCount(hp)
            let ks = intKeys(hp)
            let pos = Self.lowerBound15(ks, cnt, key)
            if pos < cnt && ks[pos] == key {
                return removeFromInternal(idx, pos, rem, sp)
            }
            stack[sp] = Self.packFrame(idx, pos)
            sp &+= 1
            idx = Int(intChildren(hp)[pos])
            rem &-= 1
        }

        // Leaf level
        let lp = leafPtr(idx)
        let cnt = leafCount(lp)
        let ks = leafKeys(lp)
        let pos = Self.lowerBound15(ks, cnt, key)
        if pos >= cnt || ks[pos] != key {
            return false
        }

        let vs = leafVals(lp)
        Self.shiftLeft64(ks, pos, cnt)
        Self.shiftLeft64(vs, pos, cnt)
        let newCnt = cnt &- 1
        setLeafCount(lp, newCnt)
        _count &-= 1

        if newCnt >= Self.MIN_KEYS {
            return true
        }

        rebalanceAfterLeafUnderflow(idx, sp)
        return true
    }

    // Cold path: key was found in internal node `targetIdx` at `targetPos`.
    // Replace with in-order predecessor (rightmost entry of left subtree -> zero shifting in leaf!).
    @inline(never)
    private func removeFromInternal(
        _ targetIdx: Int,
        _ targetPos: Int,
        _ remLevels: Int,
        _ depth: Int
    ) -> Bool {
        let stack = pathBuf.unsafelyUnwrapped
        var sp = depth
        let targetHp = intHotPtr(targetIdx)
        stack[sp] = Self.packFrame(targetIdx, targetPos)
        sp &+= 1

        var cur = Int(intChildren(targetHp)[targetPos])
        var rem = remLevels &- 1

        while rem > 0 {
            let hp = intHotPtr(cur)
            let cCnt = intCount(hp)
            stack[sp] = Self.packFrame(cur, cCnt)
            sp &+= 1
            cur = Int(intChildren(hp)[cCnt])
            rem &-= 1
        }

        // `cur` is the predecessor leaf: pop its last entry (zero shifting!)
        let lp = leafPtr(cur)
        let lCnt = leafCount(lp)
        let last = lCnt &- 1
        intKeys(targetHp)[targetPos] = leafKeys(lp)[last]
        intVals(targetIdx)[targetPos] = leafVals(lp)[last]
        setLeafCount(lp, last)
        _count &-= 1

        if last >= Self.MIN_KEYS {
            return true
        }

        rebalanceAfterLeafUnderflow(cur, sp)
        return true
    }

    // Cold path: non-root leaf `leafIdx` has dropped to 14 keys.
    // Bulk-borrow half of sibling's surplus (eliminating repeated rebalances), or merge and propagate up.
    @inline(never)
    private func rebalanceAfterLeafUnderflow(
        _ leafIdx: Int,
        _ depth: Int
    ) {
        let stack = pathBuf.unsafelyUnwrapped
        var sp = depth &- 1
        let frame = stack[sp]
        let pIdx = Int(frame & 0xFFFF_FFFF)
        let childPos = Int(frame &>> 32)

        let php = intHotPtr(pIdx)
        let pCnt = intCount(php)
        let pks = intKeys(php)
        let pvs = intVals(pIdx)
        let pcs = intChildren(php)

        let curPtr = leafPtr(leafIdx)
        let curKeys = leafKeys(curPtr)
        let curVals = leafVals(curPtr)

        // 1. Try bulk-borrowing from right sibling
        if childPos < pCnt {
            let rightIdx = Int(pcs[childPos &+ 1])
            let rp = leafPtr(rightIdx)
            let rCnt = leafCount(rp)
            if rCnt > Self.MIN_KEYS {
                let move = (rCnt &- 14) &>> 1
                let m = move &- 1
                let rks = leafKeys(rp)
                let rvs = leafVals(rp)

                curKeys[14] = pks[childPos]
                curVals[14] = pvs[childPos]
                if m > 0 {
                    Self.copy64(curKeys.advanced(by: 15), rks, m)
                    Self.copy64(curVals.advanced(by: 15), rvs, m)
                }
                pks[childPos] = rks[m]
                pvs[childPos] = rvs[m]
                Self.shiftLeftBy64(rks, rCnt, move)
                Self.shiftLeftBy64(rvs, rCnt, move)
                setLeafCount(curPtr, 14 &+ move)
                setLeafCount(rp, rCnt &- move)
                return
            }
        }

        // 2. Try bulk-borrowing from left sibling
        if childPos > 0 {
            let leftIdx = Int(pcs[childPos &- 1])
            let lp = leafPtr(leftIdx)
            let lCnt = leafCount(lp)
            if lCnt > Self.MIN_KEYS {
                let move = (lCnt &- 14) &>> 1
                let m = move &- 1
                let lks = leafKeys(lp)
                let lvs = leafVals(lp)

                Self.shiftRightBy64(curKeys, 14, move)
                Self.shiftRightBy64(curVals, 14, move)
                curKeys[m] = pks[childPos &- 1]
                curVals[m] = pvs[childPos &- 1]
                if m > 0 {
                    Self.copy64(curKeys, lks.advanced(by: lCnt &- m), m)
                    Self.copy64(curVals, lvs.advanced(by: lCnt &- m), m)
                }
                pks[childPos &- 1] = lks[lCnt &- move]
                pvs[childPos &- 1] = lvs[lCnt &- move]
                setLeafCount(lp, lCnt &- move)
                setLeafCount(curPtr, 14 &+ move)
                return
            }
        }

        // 3. Merge with a sibling (14 + 1 + 15 = 30 keys)
        let sepPos: Int
        if childPos < pCnt {
            // Merge cur (14) + sep + right (15) into cur
            sepPos = childPos
            let rightU32 = pcs[childPos &+ 1]
            let rp = leafPtr(Int(rightU32))
            curKeys[14] = pks[sepPos]
            curVals[14] = pvs[sepPos]
            Self.copy64(curKeys.advanced(by: 15), leafKeys(rp), 15)
            Self.copy64(curVals.advanced(by: 15), leafVals(rp), 15)
            setLeafCount(curPtr, 30)
            freeLeaf(rightU32)
        } else {
            // Merge left (15) + sep + cur (14) into left
            sepPos = childPos &- 1
            let leftIdx = Int(pcs[sepPos])
            let lp = leafPtr(leftIdx)
            let lks = leafKeys(lp)
            let lvs = leafVals(lp)
            lks[15] = pks[sepPos]
            lvs[15] = pvs[sepPos]
            Self.copy64(lks.advanced(by: 16), curKeys, 14)
            Self.copy64(lvs.advanced(by: 16), curVals, 14)
            setLeafCount(lp, 30)
            freeLeaf(UInt32(truncatingIfNeeded: leafIdx))
        }

        // Remove separator `sepPos` and right child `sepPos + 1` from parent `pIdx`
        Self.shiftLeft64(pks, sepPos, pCnt)
        Self.shiftLeft64(pvs, sepPos, pCnt)
        Self.shiftLeft32(pcs, sepPos &+ 1, pCnt &+ 1)
        let newPCnt = pCnt &- 1
        setIntCount(php, newPCnt)

        var curIntIdx = pIdx
        var curIntCnt = newPCnt

        // Propagate up through internal ancestors while underfull
        while sp > 0 {
            if curIntCnt >= Self.MIN_KEYS {
                return
            }

            sp &-= 1
            let aFrame = stack[sp]
            let ancIdx = Int(aFrame & 0xFFFF_FFFF)
            let cPos = Int(aFrame &>> 32)

            let ahp = intHotPtr(ancIdx)
            let aCnt = intCount(ahp)
            let aks = intKeys(ahp)
            let avs = intVals(ancIdx)
            let acs = intChildren(ahp)

            let chp = intHotPtr(curIntIdx)
            let cks = intKeys(chp)
            let cvs = intVals(curIntIdx)
            let ccs = intChildren(chp)

            // 1. Try bulk-borrowing from right internal sibling
            if cPos < aCnt {
                let rightIdx = Int(acs[cPos &+ 1])
                let rhp = intHotPtr(rightIdx)
                let rCnt = intCount(rhp)
                if rCnt > Self.MIN_KEYS {
                    let move = (rCnt &- 14) &>> 1
                    let m = move &- 1
                    let rks = intKeys(rhp)
                    let rvs = intVals(rightIdx)
                    let rcs = intChildren(rhp)

                    cks[14] = aks[cPos]
                    cvs[14] = avs[cPos]
                    if m > 0 {
                        Self.copy64(cks.advanced(by: 15), rks, m)
                        Self.copy64(cvs.advanced(by: 15), rvs, m)
                    }
                    Self.copy32(ccs.advanced(by: 15), rcs, move)
                    aks[cPos] = rks[m]
                    avs[cPos] = rvs[m]
                    Self.shiftLeftBy64(rks, rCnt, move)
                    Self.shiftLeftBy64(rvs, rCnt, move)
                    Self.shiftLeftBy32(rcs, rCnt &+ 1, move)
                    setIntCount(chp, 14 &+ move)
                    setIntCount(rhp, rCnt &- move)
                    return
                }
            }

            // 2. Try bulk-borrowing from left internal sibling
            if cPos > 0 {
                let leftIdx = Int(acs[cPos &- 1])
                let lhp = intHotPtr(leftIdx)
                let lCnt = intCount(lhp)
                if lCnt > Self.MIN_KEYS {
                    let move = (lCnt &- 14) &>> 1
                    let m = move &- 1
                    let lks = intKeys(lhp)
                    let lvs = intVals(leftIdx)
                    let lcs = intChildren(lhp)

                    Self.shiftRightBy64(cks, 14, move)
                    Self.shiftRightBy64(cvs, 14, move)
                    Self.shiftRightBy32(ccs, 15, move)
                    cks[m] = aks[cPos &- 1]
                    cvs[m] = avs[cPos &- 1]
                    if m > 0 {
                        Self.copy64(cks, lks.advanced(by: lCnt &- m), m)
                        Self.copy64(cvs, lvs.advanced(by: lCnt &- m), m)
                    }
                    Self.copy32(ccs, lcs.advanced(by: lCnt &+ 1 &- move), move)
                    aks[cPos &- 1] = lks[lCnt &- move]
                    avs[cPos &- 1] = lvs[lCnt &- move]
                    setIntCount(lhp, lCnt &- move)
                    setIntCount(chp, 14 &+ move)
                    return
                }
            }

            // 3. Merge two internal nodes (14 + 1 + 15 = 30 keys, 31 children)
            let aSep: Int
            if cPos < aCnt {
                aSep = cPos
                let rightU32 = acs[cPos &+ 1]
                let rightIdx = Int(rightU32)
                let rhp = intHotPtr(rightIdx)
                cks[14] = aks[aSep]
                cvs[14] = avs[aSep]
                Self.copy64(cks.advanced(by: 15), intKeys(rhp), 15)
                Self.copy64(cvs.advanced(by: 15), intVals(rightIdx), 15)
                Self.copy32(ccs.advanced(by: 15), intChildren(rhp), 16)
                setIntCount(chp, 30)
                freeInternal(rightU32)
            } else {
                aSep = cPos &- 1
                let leftIdx = Int(acs[aSep])
                let lhp = intHotPtr(leftIdx)
                let lks = intKeys(lhp)
                let lvs = intVals(leftIdx)
                let lcs = intChildren(lhp)
                lks[15] = aks[aSep]
                lvs[15] = avs[aSep]
                Self.copy64(lks.advanced(by: 16), cks, 14)
                Self.copy64(lvs.advanced(by: 16), cvs, 14)
                Self.copy32(lcs.advanced(by: 16), ccs, 15)
                setIntCount(lhp, 30)
                freeInternal(UInt32(truncatingIfNeeded: curIntIdx))
            }

            Self.shiftLeft64(aks, aSep, aCnt)
            Self.shiftLeft64(avs, aSep, aCnt)
            Self.shiftLeft32(acs, aSep &+ 1, aCnt &+ 1)
            curIntIdx = ancIdx
            curIntCnt = aCnt &- 1
            setIntCount(ahp, curIntCnt)
        }

        // Reached the root internal node: shrink tree height if root is now empty
        if curIntCnt == 0 {
            let rhp = intHotPtr(curIntIdx)
            let newRoot = intChildren(rhp)[0]
            freeInternal(UInt32(truncatingIfNeeded: curIntIdx))
            root = newRoot
            _height &-= 1
        }
    }

    // ------------------------------------------------------------------ range

    func range(
        _ lo: Int64,
        _ hi: Int64,
        _ outKeys: UnsafeMutablePointer<Int64>,
        _ outVals: UnsafeMutablePointer<Int64>,
        _ limit: Int
    ) -> Int {
        let h = _height
        if limit <= 0 || lo > hi || h == 0 {
            return 0
        }

        if h == 1 {
            let lp = leafPtr(Int(root))
            let cnt = leafCount(lp)
            let ks = leafKeys(lp)
            let pos = Self.lowerBoundRoot(ks, cnt, lo)
            if pos >= cnt { return 0 }
            let vs = leafVals(lp)
            let avail = cnt &- pos
            if avail <= limit && ks[cnt &- 1] <= hi {
                Self.copy64(outKeys, ks.advanced(by: pos), avail)
                Self.copy64(outVals, vs.advanced(by: pos), avail)
                return avail
            }
            let end = pos &+ (avail < limit ? avail : limit)
            var written = 0
            var j = pos
            while j < end && ks[j] <= hi {
                outKeys[written] = ks[j]
                outVals[written] = vs[j]
                written &+= 1
                j &+= 1
            }
            return written
        }

        let stack = pathBuf.unsafelyUnwrapped
        var idx = Int(root)
        var sp = 0
        let leafParentDepth = h &- 2
        var written = 0
        var exactInternalHit = false

        // Phase 1: Seek to `lo`
        var depth = 0
        while depth < h &- 1 {
            let hp = intHotPtr(idx)
            let cnt = intCount(hp)
            let ks = intKeys(hp)
            let pos = depth == 0 ? Self.lowerBoundRoot(ks, cnt, lo) : Self.lowerBound15(ks, cnt, lo)
            stack[sp] = Self.packFrame(idx, pos)
            sp &+= 1
            if pos < cnt && ks[pos] == lo {
                // All keys in children[pos] are strictly < lo; start emitting at ks[pos]
                exactInternalHit = true
                break
            }
            idx = Int(intChildren(hp)[pos])
            depth &+= 1
        }

        if !exactInternalHit {
            // Reached starting leaf
            let lp = leafPtr(idx)
            let cnt = leafCount(lp)
            let ks = leafKeys(lp)
            let pos = Self.lowerBound15(ks, cnt, lo)
            if pos < cnt {
                let vs = leafVals(lp)
                let avail = cnt &- pos
                if avail <= limit && ks[cnt &- 1] <= hi {
                    Self.copy64(outKeys, ks.advanced(by: pos), avail)
                    Self.copy64(outVals, vs.advanced(by: pos), avail)
                    written = avail
                    if written == limit { return written }
                } else {
                    let end = pos &+ (avail < limit ? avail : limit)
                    var j = pos
                    while j < end && ks[j] <= hi {
                        outKeys[written] = ks[j]
                        outVals[written] = vs[j]
                        written &+= 1
                        j &+= 1
                    }
                    return written
                }
            }
        }

        // Phase 2: Iterative in-order scan with specialized tight loop at leaf-parent level
        while sp > 0 {
            let topDepth = sp &- 1
            let frame = stack[topDepth]
            let pIdx = Int(frame & 0xFFFF_FFFF)
            var pos = Int(frame &>> 32)

            let hp = intHotPtr(pIdx)
            let pCnt = intCount(hp)
            if pos >= pCnt {
                sp = topDepth
                continue
            }

            let pks = intKeys(hp)
            let pvs = intVals(pIdx)
            let pcs = intChildren(hp)

            if topDepth == leafParentDepth {
                // Tight loop across all remaining (separator, leaf) pairs under this leaf-parent
                while pos < pCnt {
                    let k = pks[pos]
                    if k > hi { return written }
                    outKeys[written] = k
                    outVals[written] = pvs[pos]
                    written &+= 1
                    if written == limit { return written }
                    pos &+= 1

                    let lp = leafPtr(Int(pcs[pos]))
                    let lCnt = leafCount(lp)
                    let lks = leafKeys(lp)
                    let lvs = leafVals(lp)
                    let rem = limit &- written
                    if lCnt <= rem && lks[lCnt &- 1] <= hi {
                        Self.copy64(outKeys.advanced(by: written), lks, lCnt)
                        Self.copy64(outVals.advanced(by: written), lvs, lCnt)
                        written &+= lCnt
                        if written == limit { return written }
                    } else {
                        let maxTake = lCnt < rem ? lCnt : rem
                        var j = 0
                        while j < maxTake && lks[j] <= hi {
                            outKeys[written] = lks[j]
                            outVals[written] = lvs[j]
                            written &+= 1
                            j &+= 1
                        }
                        return written
                    }
                }
                sp = topDepth
                continue
            }

            // Upper internal node: emit one separator and descend leftmost to a leaf
            let k = pks[pos]
            if k > hi { return written }
            outKeys[written] = k
            outVals[written] = pvs[pos]
            written &+= 1
            if written == limit { return written }
            pos &+= 1
            stack[topDepth] = Self.packFrame(pIdx, pos)

            var cur = Int(pcs[pos])
            var d = topDepth &+ 1
            while d < h &- 1 {
                stack[sp] = Self.packFrame(cur, 0)
                sp &+= 1
                cur = Int(intChildren(intHotPtr(cur))[0])
                d &+= 1
            }

            // Emit leftmost leaf of this subtree
            let lp = leafPtr(cur)
            let lCnt = leafCount(lp)
            let lks = leafKeys(lp)
            let lvs = leafVals(lp)
            let rem = limit &- written
            if lCnt <= rem && lks[lCnt &- 1] <= hi {
                Self.copy64(outKeys.advanced(by: written), lks, lCnt)
                Self.copy64(outVals.advanced(by: written), lvs, lCnt)
                written &+= lCnt
                if written == limit { return written }
            } else {
                let maxTake = lCnt < rem ? lCnt : rem
                var j = 0
                while j < maxTake && lks[j] <= hi {
                    outKeys[written] = lks[j]
                    outVals[written] = lvs[j]
                    written &+= 1
                    j &+= 1
                }
                return written
            }
        }

        return written
    }
}
