import { memo as p, notUndefined as O, approxEqual as I, debounce as A } from "./utils.js";
const y = (r) => {
  const { offsetWidth: h, offsetHeight: e } = r;
  return { width: h, height: e };
}, F = (r) => r, R = (r) => {
  const h = Math.max(r.startIndex - r.overscan, 0), e = Math.min(r.endIndex + r.overscan, r.count - 1), s = [];
  for (let t = h; t <= e; t++)
    s.push(t);
  return s;
}, D = (r, h) => {
  const e = r.scrollElement;
  if (!e)
    return;
  const s = r.targetWindow;
  if (!s)
    return;
  const t = (i) => {
    const { width: o, height: a } = i;
    h({ width: Math.round(o), height: Math.round(a) });
  };
  if (t(y(e)), !s.ResizeObserver)
    return () => {
    };
  const n = new s.ResizeObserver((i) => {
    const o = () => {
      const a = i[0];
      if (a != null && a.borderBoxSize) {
        const u = a.borderBoxSize[0];
        if (u) {
          t({ width: u.inlineSize, height: u.blockSize });
          return;
        }
      }
      t(y(e));
    };
    r.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(o) : o();
  });
  return n.observe(e, { box: "border-box" }), () => {
    n.unobserve(e);
  };
}, M = {
  passive: !0
}, w = typeof window > "u" ? !0 : "onscrollend" in window, k = (r, h) => {
  const e = r.scrollElement;
  if (!e)
    return;
  const s = r.targetWindow;
  if (!s)
    return;
  let t = 0;
  const n = r.options.useScrollendEvent && w ? () => {
  } : A(
    s,
    () => {
      h(t, !1);
    },
    r.options.isScrollingResetDelay
  ), i = (c) => () => {
    const { horizontal: m, isRtl: l } = r.options;
    t = m ? e.scrollLeft * (l && -1 || 1) : e.scrollTop, n(), h(t, c);
  }, o = i(!0), a = i(!1);
  e.addEventListener("scroll", o, M);
  const u = r.options.useScrollendEvent && w;
  return u && e.addEventListener("scrollend", a, M), () => {
    e.removeEventListener("scroll", o), u && e.removeEventListener("scrollend", a);
  };
}, _ = (r, h, e) => {
  if (h != null && h.borderBoxSize) {
    const s = h.borderBoxSize[0];
    if (s)
      return Math.round(
        s[e.options.horizontal ? "inlineSize" : "blockSize"]
      );
  }
  return r[e.options.horizontal ? "offsetWidth" : "offsetHeight"];
}, T = (r, {
  adjustments: h = 0,
  behavior: e
}, s) => {
  var t, n;
  const i = r + h;
  (n = (t = s.scrollElement) == null ? void 0 : t.scrollTo) == null || n.call(t, {
    [s.options.horizontal ? "left" : "top"]: i,
    behavior: e
  });
};
class L {
  constructor(h) {
    this.unsubs = [], this.scrollElement = null, this.targetWindow = null, this.isScrolling = !1, this.currentScrollToIndex = null, this.measurementsCache = [], this.itemSizeCache = /* @__PURE__ */ new Map(), this.laneAssignments = /* @__PURE__ */ new Map(), this.pendingMeasuredCacheIndexes = [], this.prevLanes = void 0, this.lanesChangedFlag = !1, this.lanesSettling = !1, this.scrollRect = null, this.scrollOffset = null, this.scrollDirection = null, this.scrollAdjustments = 0, this.elementsCache = /* @__PURE__ */ new Map(), this.observer = /* @__PURE__ */ (() => {
      let e = null;
      const s = () => e || (!this.targetWindow || !this.targetWindow.ResizeObserver ? null : e = new this.targetWindow.ResizeObserver((t) => {
        t.forEach((n) => {
          const i = () => {
            this._measureElement(n.target, n);
          };
          this.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(i) : i();
        });
      }));
      return {
        disconnect: () => {
          var t;
          (t = s()) == null || t.disconnect(), e = null;
        },
        observe: (t) => {
          var n;
          return (n = s()) == null ? void 0 : n.observe(t, { box: "border-box" });
        },
        unobserve: (t) => {
          var n;
          return (n = s()) == null ? void 0 : n.unobserve(t);
        }
      };
    })(), this.range = null, this.setOptions = (e) => {
      Object.entries(e).forEach(([s, t]) => {
        typeof t > "u" && delete e[s];
      }), this.options = {
        debug: !1,
        initialOffset: 0,
        overscan: 1,
        paddingStart: 0,
        paddingEnd: 0,
        scrollPaddingStart: 0,
        scrollPaddingEnd: 0,
        horizontal: !1,
        getItemKey: F,
        rangeExtractor: R,
        onChange: () => {
        },
        measureElement: _,
        initialRect: { width: 0, height: 0 },
        scrollMargin: 0,
        gap: 0,
        indexAttribute: "data-index",
        initialMeasurementsCache: [],
        lanes: 1,
        isScrollingResetDelay: 150,
        enabled: !0,
        isRtl: !1,
        useScrollendEvent: !1,
        useAnimationFrameWithResizeObserver: !1,
        ...e
      };
    }, this.notify = (e) => {
      var s, t;
      (t = (s = this.options).onChange) == null || t.call(s, this, e);
    }, this.maybeNotify = p(
      () => (this.calculateRange(), [
        this.isScrolling,
        this.range ? this.range.startIndex : null,
        this.range ? this.range.endIndex : null
      ]),
      (e) => {
        this.notify(e);
      },
      {
        key: process.env.NODE_ENV !== "production" && "maybeNotify",
        debug: () => this.options.debug,
        initialDeps: [
          this.isScrolling,
          this.range ? this.range.startIndex : null,
          this.range ? this.range.endIndex : null
        ]
      }
    ), this.cleanup = () => {
      this.unsubs.filter(Boolean).forEach((e) => e()), this.unsubs = [], this.observer.disconnect(), this.scrollElement = null, this.targetWindow = null;
    }, this._didMount = () => () => {
      this.cleanup();
    }, this._willUpdate = () => {
      var e;
      const s = this.options.enabled ? this.options.getScrollElement() : null;
      if (this.scrollElement !== s) {
        if (this.cleanup(), !s) {
          this.maybeNotify();
          return;
        }
        this.scrollElement = s, this.scrollElement && "ownerDocument" in this.scrollElement ? this.targetWindow = this.scrollElement.ownerDocument.defaultView : this.targetWindow = ((e = this.scrollElement) == null ? void 0 : e.window) ?? null, this.elementsCache.forEach((t) => {
          this.observer.observe(t);
        }), this.unsubs.push(
          this.options.observeElementRect(this, (t) => {
            this.scrollRect = t, this.maybeNotify();
          })
        ), this.unsubs.push(
          this.options.observeElementOffset(this, (t, n) => {
            this.scrollAdjustments = 0, this.scrollDirection = n ? this.getScrollOffset() < t ? "forward" : "backward" : null, this.scrollOffset = t, this.isScrolling = n, this.maybeNotify();
          })
        ), this._scrollToOffset(this.getScrollOffset(), {
          adjustments: void 0,
          behavior: void 0
        });
      }
    }, this.getSize = () => this.options.enabled ? (this.scrollRect = this.scrollRect ?? this.options.initialRect, this.scrollRect[this.options.horizontal ? "width" : "height"]) : (this.scrollRect = null, 0), this.getScrollOffset = () => this.options.enabled ? (this.scrollOffset = this.scrollOffset ?? (typeof this.options.initialOffset == "function" ? this.options.initialOffset() : this.options.initialOffset), this.scrollOffset) : (this.scrollOffset = null, 0), this.getFurthestMeasurement = (e, s) => {
      const t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
      for (let i = s - 1; i >= 0; i--) {
        const o = e[i];
        if (t.has(o.lane))
          continue;
        const a = n.get(
          o.lane
        );
        if (a == null || o.end > a.end ? n.set(o.lane, o) : o.end < a.end && t.set(o.lane, !0), t.size === this.options.lanes)
          break;
      }
      return n.size === this.options.lanes ? Array.from(n.values()).sort((i, o) => i.end === o.end ? i.index - o.index : i.end - o.end)[0] : void 0;
    }, this.getMeasurementOptions = p(
      () => [
        this.options.count,
        this.options.paddingStart,
        this.options.scrollMargin,
        this.options.getItemKey,
        this.options.enabled,
        this.options.lanes
      ],
      (e, s, t, n, i, o) => (this.prevLanes !== void 0 && this.prevLanes !== o && (this.lanesChangedFlag = !0), this.prevLanes = o, this.pendingMeasuredCacheIndexes = [], {
        count: e,
        paddingStart: s,
        scrollMargin: t,
        getItemKey: n,
        enabled: i,
        lanes: o
      }),
      {
        key: !1
      }
    ), this.getMeasurements = p(
      () => [this.getMeasurementOptions(), this.itemSizeCache],
      ({ count: e, paddingStart: s, scrollMargin: t, getItemKey: n, enabled: i, lanes: o }, a) => {
        if (!i)
          return this.measurementsCache = [], this.itemSizeCache.clear(), this.laneAssignments.clear(), [];
        if (this.laneAssignments.size > e)
          for (const l of this.laneAssignments.keys())
            l >= e && this.laneAssignments.delete(l);
        this.lanesChangedFlag && (this.lanesChangedFlag = !1, this.lanesSettling = !0, this.measurementsCache = [], this.itemSizeCache.clear(), this.laneAssignments.clear(), this.pendingMeasuredCacheIndexes = []), this.measurementsCache.length === 0 && !this.lanesSettling && (this.measurementsCache = this.options.initialMeasurementsCache, this.measurementsCache.forEach((l) => {
          this.itemSizeCache.set(l.key, l.size);
        }));
        const u = this.lanesSettling ? 0 : this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;
        this.pendingMeasuredCacheIndexes = [], this.lanesSettling && this.measurementsCache.length === e && (this.lanesSettling = !1);
        const c = this.measurementsCache.slice(0, u), m = new Array(o).fill(
          void 0
        );
        for (let l = 0; l < u; l++) {
          const f = c[l];
          f && (m[f.lane] = l);
        }
        for (let l = u; l < e; l++) {
          const f = n(l), v = this.laneAssignments.get(l);
          let d, b;
          if (v !== void 0 && this.options.lanes > 1) {
            d = v;
            const g = m[d], x = g !== void 0 ? c[g] : void 0;
            b = x ? x.end + this.options.gap : s + t;
          } else {
            const g = this.options.lanes === 1 ? c[l - 1] : this.getFurthestMeasurement(c, l);
            b = g ? g.end + this.options.gap : s + t, d = g ? g.lane : l % this.options.lanes, this.options.lanes > 1 && this.laneAssignments.set(l, d);
          }
          const E = a.get(f), S = typeof E == "number" ? E : this.options.estimateSize(l), C = b + S;
          c[l] = {
            index: l,
            start: b,
            size: S,
            end: C,
            key: f,
            lane: d
          }, m[d] = l;
        }
        return this.measurementsCache = c, c;
      },
      {
        key: process.env.NODE_ENV !== "production" && "getMeasurements",
        debug: () => this.options.debug
      }
    ), this.calculateRange = p(
      () => [
        this.getMeasurements(),
        this.getSize(),
        this.getScrollOffset(),
        this.options.lanes
      ],
      (e, s, t, n) => this.range = e.length > 0 && s > 0 ? W({
        measurements: e,
        outerSize: s,
        scrollOffset: t,
        lanes: n
      }) : null,
      {
        key: process.env.NODE_ENV !== "production" && "calculateRange",
        debug: () => this.options.debug
      }
    ), this.getVirtualIndexes = p(
      () => {
        let e = null, s = null;
        const t = this.calculateRange();
        return t && (e = t.startIndex, s = t.endIndex), this.maybeNotify.updateDeps([this.isScrolling, e, s]), [
          this.options.rangeExtractor,
          this.options.overscan,
          this.options.count,
          e,
          s
        ];
      },
      (e, s, t, n, i) => n === null || i === null ? [] : e({
        startIndex: n,
        endIndex: i,
        overscan: s,
        count: t
      }),
      {
        key: process.env.NODE_ENV !== "production" && "getVirtualIndexes",
        debug: () => this.options.debug
      }
    ), this.indexFromElement = (e) => {
      const s = this.options.indexAttribute, t = e.getAttribute(s);
      return t ? parseInt(t, 10) : (console.warn(
        `Missing attribute name '${s}={index}' on measured element.`
      ), -1);
    }, this._measureElement = (e, s) => {
      const t = this.indexFromElement(e), n = this.measurementsCache[t];
      if (!n)
        return;
      const i = n.key, o = this.elementsCache.get(i);
      o !== e && (o && this.observer.unobserve(o), this.observer.observe(e), this.elementsCache.set(i, e)), e.isConnected && this.resizeItem(t, this.options.measureElement(e, s, this));
    }, this.resizeItem = (e, s) => {
      const t = this.measurementsCache[e];
      if (!t)
        return;
      const n = this.itemSizeCache.get(t.key) ?? t.size, i = s - n;
      i !== 0 && ((this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(t, i, this) : t.start < this.getScrollOffset() + this.scrollAdjustments) && (process.env.NODE_ENV !== "production" && this.options.debug && console.info("correction", i), this._scrollToOffset(this.getScrollOffset(), {
        adjustments: this.scrollAdjustments += i,
        behavior: void 0
      })), this.pendingMeasuredCacheIndexes.push(t.index), this.itemSizeCache = new Map(this.itemSizeCache.set(t.key, s)), this.notify(!1));
    }, this.measureElement = (e) => {
      if (!e) {
        this.elementsCache.forEach((s, t) => {
          s.isConnected || (this.observer.unobserve(s), this.elementsCache.delete(t));
        });
        return;
      }
      this._measureElement(e, void 0);
    }, this.getVirtualItems = p(
      () => [this.getVirtualIndexes(), this.getMeasurements()],
      (e, s) => {
        const t = [];
        for (let n = 0, i = e.length; n < i; n++) {
          const o = e[n], a = s[o];
          t.push(a);
        }
        return t;
      },
      {
        key: process.env.NODE_ENV !== "production" && "getVirtualItems",
        debug: () => this.options.debug
      }
    ), this.getVirtualItemForOffset = (e) => {
      const s = this.getMeasurements();
      if (s.length !== 0)
        return O(
          s[z(
            0,
            s.length - 1,
            (t) => O(s[t]).start,
            e
          )]
        );
    }, this.getMaxScrollOffset = () => {
      if (!this.scrollElement) return 0;
      if ("scrollHeight" in this.scrollElement)
        return this.options.horizontal ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth : this.scrollElement.scrollHeight - this.scrollElement.clientHeight;
      {
        const e = this.scrollElement.document.documentElement;
        return this.options.horizontal ? e.scrollWidth - this.scrollElement.innerWidth : e.scrollHeight - this.scrollElement.innerHeight;
      }
    }, this.getOffsetForAlignment = (e, s, t = 0) => {
      if (!this.scrollElement) return 0;
      const n = this.getSize(), i = this.getScrollOffset();
      s === "auto" && (s = e >= i + n ? "end" : "start"), s === "center" ? e += (t - n) / 2 : s === "end" && (e -= n);
      const o = this.getMaxScrollOffset();
      return Math.max(Math.min(o, e), 0);
    }, this.getOffsetForIndex = (e, s = "auto") => {
      e = Math.max(0, Math.min(e, this.options.count - 1));
      const t = this.measurementsCache[e];
      if (!t)
        return;
      const n = this.getSize(), i = this.getScrollOffset();
      if (s === "auto")
        if (t.end >= i + n - this.options.scrollPaddingEnd)
          s = "end";
        else if (t.start <= i + this.options.scrollPaddingStart)
          s = "start";
        else
          return [i, s];
      if (s === "end" && e === this.options.count - 1)
        return [this.getMaxScrollOffset(), s];
      const o = s === "end" ? t.end + this.options.scrollPaddingEnd : t.start - this.options.scrollPaddingStart;
      return [
        this.getOffsetForAlignment(o, s, t.size),
        s
      ];
    }, this.isDynamicMode = () => this.elementsCache.size > 0, this.scrollToOffset = (e, { align: s = "start", behavior: t } = {}) => {
      t === "smooth" && this.isDynamicMode() && console.warn(
        "The `smooth` scroll behavior is not fully supported with dynamic size."
      ), this._scrollToOffset(this.getOffsetForAlignment(e, s), {
        adjustments: void 0,
        behavior: t
      });
    }, this.scrollToIndex = (e, { align: s = "auto", behavior: t } = {}) => {
      t === "smooth" && this.isDynamicMode() && console.warn(
        "The `smooth` scroll behavior is not fully supported with dynamic size."
      ), e = Math.max(0, Math.min(e, this.options.count - 1)), this.currentScrollToIndex = e;
      let n = 0;
      const i = 10, o = (u) => {
        if (!this.targetWindow) return;
        const c = this.getOffsetForIndex(e, u);
        if (!c) {
          console.warn("Failed to get offset for index:", e);
          return;
        }
        const [m, l] = c;
        this._scrollToOffset(m, { adjustments: void 0, behavior: t }), this.targetWindow.requestAnimationFrame(() => {
          const f = () => {
            if (this.currentScrollToIndex !== e) return;
            const v = this.getScrollOffset(), d = this.getOffsetForIndex(e, l);
            if (!d) {
              console.warn("Failed to get offset for index:", e);
              return;
            }
            I(d[0], v) || a(l);
          };
          this.isDynamicMode() ? this.targetWindow.requestAnimationFrame(f) : f();
        });
      }, a = (u) => {
        this.targetWindow && this.currentScrollToIndex === e && (n++, n < i ? (process.env.NODE_ENV !== "production" && this.options.debug && console.info("Schedule retry", n, i), this.targetWindow.requestAnimationFrame(() => o(u))) : console.warn(
          `Failed to scroll to index ${e} after ${i} attempts.`
        ));
      };
      o(s);
    }, this.scrollBy = (e, { behavior: s } = {}) => {
      s === "smooth" && this.isDynamicMode() && console.warn(
        "The `smooth` scroll behavior is not fully supported with dynamic size."
      ), this._scrollToOffset(this.getScrollOffset() + e, {
        adjustments: void 0,
        behavior: s
      });
    }, this.getTotalSize = () => {
      var e;
      const s = this.getMeasurements();
      let t;
      if (s.length === 0)
        t = this.options.paddingStart;
      else if (this.options.lanes === 1)
        t = ((e = s[s.length - 1]) == null ? void 0 : e.end) ?? 0;
      else {
        const n = Array(this.options.lanes).fill(null);
        let i = s.length - 1;
        for (; i >= 0 && n.some((o) => o === null); ) {
          const o = s[i];
          n[o.lane] === null && (n[o.lane] = o.end), i--;
        }
        t = Math.max(...n.filter((o) => o !== null));
      }
      return Math.max(
        t - this.options.scrollMargin + this.options.paddingEnd,
        0
      );
    }, this._scrollToOffset = (e, {
      adjustments: s,
      behavior: t
    }) => {
      this.options.scrollToFn(e, { behavior: t, adjustments: s }, this);
    }, this.measure = () => {
      this.itemSizeCache = /* @__PURE__ */ new Map(), this.laneAssignments = /* @__PURE__ */ new Map(), this.notify(!1);
    }, this.setOptions(h);
  }
}
const z = (r, h, e, s) => {
  for (; r <= h; ) {
    const t = (r + h) / 2 | 0, n = e(t);
    if (n < s)
      r = t + 1;
    else if (n > s)
      h = t - 1;
    else
      return t;
  }
  return r > 0 ? r - 1 : 0;
};
function W({
  measurements: r,
  outerSize: h,
  scrollOffset: e,
  lanes: s
}) {
  const t = r.length - 1, n = (a) => r[a].start;
  if (r.length <= s)
    return {
      startIndex: 0,
      endIndex: t
    };
  let i = z(
    0,
    t,
    n,
    e
  ), o = i;
  if (s === 1)
    for (; o < t && r[o].end < e + h; )
      o++;
  else if (s > 1) {
    const a = Array(s).fill(0);
    for (; o < t && a.some((c) => c < e + h); ) {
      const c = r[o];
      a[c.lane] = c.end, o++;
    }
    const u = Array(s).fill(e + h);
    for (; i >= 0 && u.some((c) => c >= e); ) {
      const c = r[i];
      u[c.lane] = c.start, i--;
    }
    i = Math.max(0, i - i % s), o = Math.min(t, o + (s - 1 - o % s));
  }
  return { startIndex: i, endIndex: o };
}
export {
  L as Virtualizer,
  I as approxEqual,
  A as debounce,
  F as defaultKeyExtractor,
  R as defaultRangeExtractor,
  T as elementScroll,
  _ as measureElement,
  p as memo,
  O as notUndefined,
  k as observeElementOffset,
  D as observeElementRect
};
