"use client";
import { memo as f, notUndefined as v, approxEqual as M, debounce as z } from "./utils.js";
const b = (r) => {
  const { offsetWidth: a, offsetHeight: e } = r;
  return { width: a, height: e };
}, w = (r) => r, I = (r) => {
  const a = Math.max(r.startIndex - r.overscan, 0), e = Math.min(r.endIndex + r.overscan, r.count - 1), s = [];
  for (let t = a; t <= e; t++)
    s.push(t);
  return s;
}, A = (r, a) => {
  const e = r.scrollElement;
  if (!e)
    return;
  const s = r.targetWindow;
  if (!s)
    return;
  const t = (n) => {
    const { width: o, height: h } = n;
    a({ width: Math.round(o), height: Math.round(h) });
  };
  if (t(b(e)), !s.ResizeObserver)
    return () => {
    };
  const i = new s.ResizeObserver((n) => {
    const o = () => {
      const h = n[0];
      if (h?.borderBoxSize) {
        const c = h.borderBoxSize[0];
        if (c) {
          t({ width: c.inlineSize, height: c.blockSize });
          return;
        }
      }
      t(b(e));
    };
    r.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(o) : o();
  });
  return i.observe(e, { box: "border-box" }), () => {
    i.unobserve(e);
  };
}, E = {
  passive: !0
}, S = typeof window > "u" ? !0 : "onscrollend" in window, F = (r, a) => {
  const e = r.scrollElement;
  if (!e)
    return;
  const s = r.targetWindow;
  if (!s)
    return;
  let t = 0;
  const i = r.options.useScrollendEvent && S ? () => {
  } : z(
    s,
    () => {
      a(t, !1);
    },
    r.options.isScrollingResetDelay
  ), n = (l) => () => {
    const { horizontal: d, isRtl: u } = r.options;
    t = d ? e.scrollLeft * (u && -1 || 1) : e.scrollTop, i(), a(t, l);
  }, o = n(!0), h = n(!1);
  h(), e.addEventListener("scroll", o, E);
  const c = r.options.useScrollendEvent && S;
  return c && e.addEventListener("scrollend", h, E), () => {
    e.removeEventListener("scroll", o), c && e.removeEventListener("scrollend", h);
  };
}, C = (r, a, e) => {
  if (a?.borderBoxSize) {
    const s = a.borderBoxSize[0];
    if (s)
      return Math.round(
        s[e.options.horizontal ? "inlineSize" : "blockSize"]
      );
  }
  return r[e.options.horizontal ? "offsetWidth" : "offsetHeight"];
}, N = (r, {
  adjustments: a = 0,
  behavior: e
}, s) => {
  var t, i;
  const n = r + a;
  (i = (t = s.scrollElement) == null ? void 0 : t.scrollTo) == null || i.call(t, {
    [s.options.horizontal ? "left" : "top"]: n,
    behavior: e
  });
};
class W {
  constructor(a) {
    this.unsubs = [], this.scrollElement = null, this.targetWindow = null, this.isScrolling = !1, this.measurementsCache = [], this.itemSizeCache = /* @__PURE__ */ new Map(), this.pendingMeasuredCacheIndexes = [], 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((i) => {
          const n = () => {
            this._measureElement(i.target, i);
          };
          this.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(n) : n();
        });
      }));
      return {
        disconnect: () => {
          var t;
          (t = s()) == null || t.disconnect(), e = null;
        },
        observe: (t) => {
          var i;
          return (i = s()) == null ? void 0 : i.observe(t, { box: "border-box" });
        },
        unobserve: (t) => {
          var i;
          return (i = s()) == null ? void 0 : i.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: w,
        rangeExtractor: I,
        onChange: () => {
        },
        measureElement: C,
        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 = f(
      () => (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._scrollToOffset(this.getScrollOffset(), {
          adjustments: void 0,
          behavior: void 0
        }), this.unsubs.push(
          this.options.observeElementRect(this, (t) => {
            this.scrollRect = t, this.maybeNotify();
          })
        ), this.unsubs.push(
          this.options.observeElementOffset(this, (t, i) => {
            this.scrollAdjustments = 0, this.scrollDirection = i ? this.getScrollOffset() < t ? "forward" : "backward" : null, this.scrollOffset = t, this.isScrolling = i, this.maybeNotify();
          })
        );
      }
    }, 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(), i = /* @__PURE__ */ new Map();
      for (let n = s - 1; n >= 0; n--) {
        const o = e[n];
        if (t.has(o.lane))
          continue;
        const h = i.get(
          o.lane
        );
        if (h == null || o.end > h.end ? i.set(o.lane, o) : o.end < h.end && t.set(o.lane, !0), t.size === this.options.lanes)
          break;
      }
      return i.size === this.options.lanes ? Array.from(i.values()).sort((n, o) => n.end === o.end ? n.index - o.index : n.end - o.end)[0] : void 0;
    }, this.getMeasurementOptions = f(
      () => [
        this.options.count,
        this.options.paddingStart,
        this.options.scrollMargin,
        this.options.getItemKey,
        this.options.enabled
      ],
      (e, s, t, i, n) => (this.pendingMeasuredCacheIndexes = [], {
        count: e,
        paddingStart: s,
        scrollMargin: t,
        getItemKey: i,
        enabled: n
      }),
      {
        key: !1
      }
    ), this.getMeasurements = f(
      () => [this.getMeasurementOptions(), this.itemSizeCache],
      ({ count: e, paddingStart: s, scrollMargin: t, getItemKey: i, enabled: n }, o) => {
        if (!n)
          return this.measurementsCache = [], this.itemSizeCache.clear(), [];
        this.measurementsCache.length === 0 && (this.measurementsCache = this.options.initialMeasurementsCache, this.measurementsCache.forEach((l) => {
          this.itemSizeCache.set(l.key, l.size);
        }));
        const h = this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;
        this.pendingMeasuredCacheIndexes = [];
        const c = this.measurementsCache.slice(0, h);
        for (let l = h; l < e; l++) {
          const d = i(l), u = this.options.lanes === 1 ? c[l - 1] : this.getFurthestMeasurement(c, l), g = u ? u.end + this.options.gap : s + t, m = o.get(d), p = typeof m == "number" ? m : this.options.estimateSize(l), O = g + p, y = u ? u.lane : l % this.options.lanes;
          c[l] = {
            index: l,
            start: g,
            size: p,
            end: O,
            key: d,
            lane: y
          };
        }
        return this.measurementsCache = c, c;
      },
      {
        key: process.env.NODE_ENV !== "production" && "getMeasurements",
        debug: () => this.options.debug
      }
    ), this.calculateRange = f(
      () => [
        this.getMeasurements(),
        this.getSize(),
        this.getScrollOffset(),
        this.options.lanes
      ],
      (e, s, t, i) => this.range = e.length > 0 && s > 0 ? R({
        measurements: e,
        outerSize: s,
        scrollOffset: t,
        lanes: i
      }) : null,
      {
        key: process.env.NODE_ENV !== "production" && "calculateRange",
        debug: () => this.options.debug
      }
    ), this.getVirtualIndexes = f(
      () => {
        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, i, n) => i === null || n === null ? [] : e({
        startIndex: i,
        endIndex: n,
        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), i = this.measurementsCache[t];
      if (!i)
        return;
      const n = i.key, o = this.elementsCache.get(n);
      o !== e && (o && this.observer.unobserve(o), this.observer.observe(e), this.elementsCache.set(n, 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 i = this.itemSizeCache.get(t.key) ?? t.size, n = s - i;
      n !== 0 && ((this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(t, n, this) : t.start < this.getScrollOffset() + this.scrollAdjustments) && (process.env.NODE_ENV !== "production" && this.options.debug && console.info("correction", n), this._scrollToOffset(this.getScrollOffset(), {
        adjustments: this.scrollAdjustments += n,
        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 = f(
      () => [this.getVirtualIndexes(), this.getMeasurements()],
      (e, s) => {
        const t = [];
        for (let i = 0, n = e.length; i < n; i++) {
          const o = e[i], h = s[o];
          t.push(h);
        }
        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 v(
          s[x(
            0,
            s.length - 1,
            (t) => v(s[t]).start,
            e
          )]
        );
    }, this.getOffsetForAlignment = (e, s, t = 0) => {
      const i = this.getSize(), n = this.getScrollOffset();
      s === "auto" && (s = e >= n + i ? "end" : "start"), s === "center" ? e += (t - i) / 2 : s === "end" && (e -= i);
      const o = this.getTotalSize() + this.options.scrollMargin - i;
      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 i = this.getSize(), n = this.getScrollOffset();
      if (s === "auto")
        if (t.end >= n + i - this.options.scrollPaddingEnd)
          s = "end";
        else if (t.start <= n + this.options.scrollPaddingStart)
          s = "start";
        else
          return [n, 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));
      let i = 0;
      const n = 10, o = (c) => {
        if (!this.targetWindow) return;
        const l = this.getOffsetForIndex(e, c);
        if (!l) {
          console.warn("Failed to get offset for index:", e);
          return;
        }
        const [d, u] = l;
        this._scrollToOffset(d, { adjustments: void 0, behavior: t }), this.targetWindow.requestAnimationFrame(() => {
          const g = this.getScrollOffset(), m = this.getOffsetForIndex(e, u);
          if (!m) {
            console.warn("Failed to get offset for index:", e);
            return;
          }
          M(m[0], g) || h(u);
        });
      }, h = (c) => {
        this.targetWindow && (i++, i < n ? (process.env.NODE_ENV !== "production" && this.options.debug && console.info("Schedule retry", i, n), this.targetWindow.requestAnimationFrame(() => o(c))) : console.warn(
          `Failed to scroll to index ${e} after ${n} 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 i = Array(this.options.lanes).fill(null);
        let n = s.length - 1;
        for (; n >= 0 && i.some((o) => o === null); ) {
          const o = s[n];
          i[o.lane] === null && (i[o.lane] = o.end), n--;
        }
        t = Math.max(...i.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.notify(!1);
    }, this.setOptions(a);
  }
}
const x = (r, a, e, s) => {
  for (; r <= a; ) {
    const t = (r + a) / 2 | 0, i = e(t);
    if (i < s)
      r = t + 1;
    else if (i > s)
      a = t - 1;
    else
      return t;
  }
  return r > 0 ? r - 1 : 0;
};
function R({
  measurements: r,
  outerSize: a,
  scrollOffset: e,
  lanes: s
}) {
  const t = r.length - 1, i = (h) => r[h].start;
  if (r.length <= s)
    return {
      startIndex: 0,
      endIndex: t
    };
  let n = x(
    0,
    t,
    i,
    e
  ), o = n;
  if (s === 1)
    for (; o < t && r[o].end < e + a; )
      o++;
  else if (s > 1) {
    const h = Array(s).fill(0);
    for (; o < t && h.some((l) => l < e + a); ) {
      const l = r[o];
      h[l.lane] = l.end, o++;
    }
    const c = Array(s).fill(e + a);
    for (; n >= 0 && c.some((l) => l >= e); ) {
      const l = r[n];
      c[l.lane] = l.start, n--;
    }
    n = Math.max(0, n - n % s), o = Math.min(t, o + (s - 1 - o % s));
  }
  return { startIndex: n, endIndex: o };
}
export {
  W as Virtualizer,
  M as approxEqual,
  z as debounce,
  w as defaultKeyExtractor,
  I as defaultRangeExtractor,
  N as elementScroll,
  C as measureElement,
  f as memo,
  v as notUndefined,
  F as observeElementOffset,
  A as observeElementRect
};
