function P(h) {
  const { totalRows: e, viewportHeight: t, scrollTop: r, rowHeight: n, overscan: i } = h, l = Math.ceil(t / n);
  let a = Math.floor(r / n) - i;
  a < 0 && (a = 0);
  let o = a + l + i * 2;
  return o > e && (o = e), o === e && a > 0 && (a = Math.max(0, o - l - i * 2)), {
    start: a,
    end: o,
    offsetY: a * n,
    totalHeight: e * n
  };
}
function V(h, e) {
  return h <= e;
}
const _ = {
  expand: "▶",
  collapse: "▼",
  sortAsc: "▲",
  sortDesc: "▼",
  sortNone: "⇅",
  submenuArrow: "▶",
  dragHandle: "⋮⋮",
  toolPanel: "☰"
};
class M {
  /**
   * Plugin dependencies - declare other plugins this one requires.
   *
   * Dependencies are validated when the plugin is attached.
   * Required dependencies throw an error if missing.
   * Optional dependencies log an info message if missing.
   *
   * @example
   * ```typescript
   * static readonly dependencies: PluginDependency[] = [
   *   { name: 'editing', required: true, reason: 'Tracks cell edits for undo/redo' },
   *   { name: 'selection', required: false, reason: 'Enables selection-based undo' },
   * ];
   * ```
   */
  static dependencies;
  /**
   * Plugin version - defaults to grid version for built-in plugins.
   * Third-party plugins can override with their own semver.
   */
  version = typeof __GRID_VERSION__ < "u" ? __GRID_VERSION__ : "dev";
  /** CSS styles to inject into the grid's shadow DOM */
  styles;
  /** Custom cell renderers keyed by type name */
  cellRenderers;
  /** Custom header renderers keyed by type name */
  headerRenderers;
  /** Custom cell editors keyed by type name */
  cellEditors;
  /** The grid instance this plugin is attached to */
  grid;
  /** Plugin configuration - merged with defaults in attach() */
  config;
  /** User-provided configuration from constructor */
  userConfig;
  /**
   * Plugin-level AbortController for event listener cleanup.
   * Created fresh in attach(), aborted in detach().
   * This ensures event listeners are properly cleaned up when plugins are re-attached.
   */
  #e;
  /**
   * Default configuration - subclasses should override this getter.
   * Note: This must be a getter (not property initializer) for proper inheritance
   * since property initializers run after parent constructor.
   */
  get defaultConfig() {
    return {};
  }
  constructor(e = {}) {
    this.userConfig = e;
  }
  /**
   * Called when the plugin is attached to a grid.
   * Override to set up event listeners, initialize state, etc.
   *
   * @example
   * ```ts
   * attach(grid: GridElement): void {
   *   super.attach(grid);
   *   // Set up document-level listeners with auto-cleanup
   *   document.addEventListener('keydown', this.handleEscape, {
   *     signal: this.disconnectSignal
   *   });
   * }
   * ```
   */
  attach(e) {
    this.#e?.abort(), this.#e = new AbortController(), this.grid = e, this.config = { ...this.defaultConfig, ...this.userConfig };
  }
  /**
   * Called when the plugin is detached from a grid.
   * Override to clean up event listeners, timers, etc.
   *
   * @example
   * ```ts
   * detach(): void {
   *   // Clean up any state not handled by disconnectSignal
   *   this.selectedRows.clear();
   *   this.cache = null;
   * }
   * ```
   */
  detach() {
    this.#e?.abort(), this.#e = void 0;
  }
  /**
   * Get another plugin instance from the same grid.
   * Use for inter-plugin communication.
   *
   * @example
   * ```ts
   * const selection = this.getPlugin(SelectionPlugin);
   * if (selection) {
   *   const selectedRows = selection.getSelectedRows();
   * }
   * ```
   */
  getPlugin(e) {
    return this.grid?.getPlugin(e);
  }
  /**
   * Emit a custom event from the grid.
   */
  emit(e, t) {
    this.grid?.dispatchEvent?.(new CustomEvent(e, { detail: t, bubbles: !0 }));
  }
  /**
   * Emit a cancelable custom event from the grid.
   * @returns `true` if the event was cancelled (preventDefault called), `false` otherwise
   */
  emitCancelable(e, t) {
    const r = new CustomEvent(e, { detail: t, bubbles: !0, cancelable: !0 });
    return this.grid?.dispatchEvent?.(r), r.defaultPrevented;
  }
  /**
   * Request a re-render of the grid.
   */
  requestRender() {
    this.grid?.requestRender?.();
  }
  /**
   * Request a re-render and restore focus styling afterward.
   * Use this when a plugin action (like expand/collapse) triggers a render
   * but needs to maintain keyboard navigation focus.
   */
  requestRenderWithFocus() {
    this.grid?.requestRenderWithFocus?.();
  }
  /**
   * Request a lightweight style update without rebuilding DOM.
   * Use this instead of requestRender() when only CSS classes need updating.
   */
  requestAfterRender() {
    this.grid?.requestAfterRender?.();
  }
  /**
   * Get the current rows from the grid.
   */
  get rows() {
    return this.grid?.rows ?? [];
  }
  /**
   * Get the original unfiltered/unprocessed rows from the grid.
   * Use this when you need all source data regardless of active filters.
   */
  get sourceRows() {
    return this.grid?.sourceRows ?? [];
  }
  /**
   * Get the current columns from the grid.
   */
  get columns() {
    return this.grid?.columns ?? [];
  }
  /**
   * Get only visible columns from the grid (excludes hidden).
   * Use this for rendering that needs to match the grid template.
   */
  get visibleColumns() {
    return this.grid?._visibleColumns ?? [];
  }
  /**
   * Get the grid as an HTMLElement for direct DOM operations.
   * Use sparingly - prefer the typed GridElementRef API when possible.
   *
   * @example
   * ```ts
   * const width = this.gridElement.clientWidth;
   * this.gridElement.classList.add('my-plugin-active');
   * ```
   */
  get gridElement() {
    return this.grid;
  }
  /**
   * Get the render root of the grid for DOM queries.
   * @deprecated Use `gridElement` instead. This getter exists only for backward compatibility.
   *
   * With Shadow DOM removed, the grid element itself is the render root.
   * All new code should use `this.gridElement` for DOM queries.
   *
   * @example
   * // OLD (deprecated)
   * const rows = this.shadowRoot?.querySelector('.rows');
   *
   * // NEW (preferred)
   * const rows = this.gridElement.querySelector('.rows');
   */
  get shadowRoot() {
    return this.gridElement;
  }
  /**
   * Get the disconnect signal for event listener cleanup.
   * This signal is aborted when the grid disconnects from the DOM.
   * Use this when adding event listeners that should be cleaned up automatically.
   *
   * Best for:
   * - Document/window-level listeners added in attach()
   * - Listeners on the grid element itself
   * - Any listener that should persist across renders
   *
   * Not needed for:
   * - Listeners on elements created in afterRender() (removed with element)
   *
   * @example
   * element.addEventListener('click', handler, { signal: this.disconnectSignal });
   * document.addEventListener('keydown', handler, { signal: this.disconnectSignal });
   */
  get disconnectSignal() {
    return this.#e?.signal ?? this.grid?.disconnectSignal;
  }
  /**
   * Get the grid-level icons configuration.
   * Returns merged icons (user config + defaults).
   */
  get gridIcons() {
    const e = this.grid?.gridConfig?.icons ?? {};
    return { ..._, ...e };
  }
  // #region Animation Helpers
  /**
   * Check if animations are enabled at the grid level.
   * Respects gridConfig.animation.mode and the CSS variable set by the grid.
   *
   * Plugins should use this to skip animations when:
   * - Animation mode is 'off' or `false`
   * - User prefers reduced motion and mode is 'reduced-motion' (default)
   *
   * @example
   * ```ts
   * private get animationStyle(): 'slide' | 'fade' | false {
   *   if (!this.isAnimationEnabled) return false;
   *   return this.config.animation ?? 'slide';
   * }
   * ```
   */
  get isAnimationEnabled() {
    const e = this.grid?.effectiveConfig?.animation?.mode ?? "reduced-motion";
    if (e === !1 || e === "off") return !1;
    if (e === !0 || e === "on") return !0;
    const t = this.gridElement;
    return t ? getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim() !== "0" : !0;
  }
  /**
   * Get the animation duration in milliseconds from CSS variable.
   * Falls back to 200ms if not set.
   *
   * Plugins can use this for their animation timing to stay consistent
   * with the grid-level animation.duration setting.
   *
   * @example
   * ```ts
   * element.animate(keyframes, { duration: this.animationDuration });
   * ```
   */
  get animationDuration() {
    const e = this.gridElement;
    if (e) {
      const t = getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(), r = parseInt(t, 10);
      if (!isNaN(r)) return r;
    }
    return 200;
  }
  // #endregion
  /**
   * Resolve an icon value to string or HTMLElement.
   * Checks plugin config first, then grid-level icons, then defaults.
   *
   * @param iconKey - The icon key in GridIcons (e.g., 'expand', 'collapse')
   * @param pluginOverride - Optional plugin-level override
   * @returns The resolved icon value
   */
  resolveIcon(e, t) {
    return t !== void 0 ? t : this.gridIcons[e];
  }
  /**
   * Set an icon value on an element.
   * Handles both string (text/HTML) and HTMLElement values.
   *
   * @param element - The element to set the icon on
   * @param icon - The icon value (string or HTMLElement)
   */
  setIcon(e, t) {
    typeof t == "string" ? e.innerHTML = t : t instanceof HTMLElement && (e.innerHTML = "", e.appendChild(t.cloneNode(!0)));
  }
  /**
   * Log a warning message.
   */
  warn(e) {
    console.warn(`[tbw-grid:${this.name}] ${e}`);
  }
  // #endregion
}
function z(h) {
  return h.meta?.utility === !0;
}
function q(h, e, t = !1) {
  const r = h[e.field];
  if (e.operator === "blank")
    return r == null || r === "";
  if (e.operator === "notBlank")
    return r != null && r !== "";
  if (r == null) return !1;
  const n = String(r), i = t ? n : n.toLowerCase(), l = t ? String(e.value) : String(e.value).toLowerCase();
  switch (e.operator) {
    // Text operators
    case "contains":
      return i.includes(l);
    case "notContains":
      return !i.includes(l);
    case "equals":
      return i === l;
    case "notEquals":
      return i !== l;
    case "startsWith":
      return i.startsWith(l);
    case "endsWith":
      return i.endsWith(l);
    // Number/Date operators (use raw numeric values)
    case "lessThan":
      return Number(r) < Number(e.value);
    case "lessThanOrEqual":
      return Number(r) <= Number(e.value);
    case "greaterThan":
      return Number(r) > Number(e.value);
    case "greaterThanOrEqual":
      return Number(r) >= Number(e.value);
    case "between":
      return Number(r) >= Number(e.value) && Number(r) <= Number(e.valueTo);
    // Set operators
    case "in":
      return Array.isArray(e.value) && e.value.includes(r);
    case "notIn":
      return Array.isArray(e.value) && !e.value.includes(r);
    default:
      return !0;
  }
}
function B(h, e, t = !1) {
  return e.length ? h.filter((r) => e.every((n) => q(r, n, t))) : h;
}
function Y(h) {
  return JSON.stringify(
    h.map((e) => ({
      field: e.field,
      operator: e.operator,
      value: e.value,
      valueTo: e.valueTo
    }))
  );
}
function H(h, e) {
  const t = /* @__PURE__ */ new Set();
  for (const r of h) {
    const n = r[e];
    n != null && t.add(n);
  }
  return [...t].sort((r, n) => typeof r == "number" && typeof n == "number" ? r - n : String(r).localeCompare(String(n)));
}
const G = '@layer tbw-plugins{tbw-grid .tbw-quick-filter-input{flex:1;max-width:300px;height:var(--tbw-input-height, 1.75rem);padding:var(--tbw-input-padding, 0 .5rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);color:var(--tbw-color-fg);font-size:var(--tbw-font-size-sm, .8125rem)}tbw-grid .tbw-quick-filter-input:focus{outline:none;border-color:var(--tbw-color-accent)}tbw-grid .header-cell.filtered:before{content:"";position:absolute;top:var(--tbw-spacing-xs, .25rem);right:var(--tbw-spacing-xs, .25rem);width:var(--tbw-indicator-size, .375rem);height:var(--tbw-indicator-size, .375rem);background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:50%}tbw-grid .tbw-filter-btn{display:inline-flex;align-items:center;justify-content:center;background:transparent;border:none;cursor:pointer;padding:2px;margin-left:var(--tbw-spacing-xs, .25rem);opacity:.4;transition:opacity .15s;color:inherit;vertical-align:middle}tbw-grid .tbw-filter-btn:hover,tbw-grid .tbw-filter-btn.active{opacity:1}tbw-grid .tbw-filter-btn.active{color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}}', $ = "@layer tbw-plugins{.tbw-filter-panel{position:fixed;background:var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));color:var(--tbw-filter-panel-fg, var(--tbw-color-fg, light-dark(#222222, #eeeeee)));border:1px solid var(--tbw-filter-panel-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-panel-radius, var(--tbw-border-radius, .25rem));box-shadow:0 4px 16px var(--tbw-filter-panel-shadow, var(--tbw-color-shadow, light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3))));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));z-index:10000;min-width:200px;max-width:280px;max-height:350px;display:flex;flex-direction:column;font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-font-size, .8125rem);transform-origin:top center}.tbw-filter-panel.tbw-filter-panel-above{transform-origin:bottom center}.tbw-filter-panel.tbw-filter-panel-animated{animation:tbw-filter-panel-enter var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}.tbw-filter-panel.tbw-filter-panel-above.tbw-filter-panel-animated{animation:tbw-filter-panel-enter-above var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}@keyframes tbw-filter-panel-enter{0%{opacity:0;transform:scaleY(.3) translateY(-10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@keyframes tbw-filter-panel-enter-above{0%{opacity:0;transform:scaleY(.3) translateY(10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@supports (anchor-name: --test){.tbw-filter-panel{position-anchor:--tbw-filter-anchor;top:anchor(bottom);left:anchor(left);margin-top:4px;position-try-fallbacks:flip-inline,flip-block,flip-block flip-inline}}.tbw-filter-search{margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-search-input{width:100%;padding:var(--tbw-button-padding, .375rem .625rem);background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-search-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-actions{display:flex;padding:var(--tbw-button-padding-sm, .25rem .125rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-bottom:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-action-btn{background:transparent;border:none;color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));cursor:pointer;font-size:var(--tbw-font-size-xs, .75rem);padding:2px 0}.tbw-filter-action-btn:hover{text-decoration:underline}.tbw-filter-values{flex:1;overflow-y:auto;margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));max-height:180px;position:relative}.tbw-filter-values-spacer{width:1px}.tbw-filter-values-content{position:absolute;top:0;left:0;right:0}.tbw-filter-value-item{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding-sm, .25rem .125rem);cursor:pointer;border-radius:3px}.tbw-filter-value-item:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-checkbox{margin:0;cursor:pointer;accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}.tbw-filter-no-match{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem)) 0;text-align:center;font-style:italic}.tbw-filter-buttons{display:flex;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding-top:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-top:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-apply-btn{flex:1;padding:var(--tbw-button-padding, .375rem .75rem);background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));color:var(--tbw-filter-accent-fg, var(--tbw-color-accent-fg, light-dark(#ffffff, #000000)));border:none;border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-filter-apply-btn:hover{filter:brightness(.9)}.tbw-filter-clear-btn{flex:1;padding:var(--tbw-button-padding, .375rem .75rem);background:transparent;color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-filter-clear-btn:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}}";
class g extends M {
  name = "filtering";
  styles = G;
  get defaultConfig() {
    return {
      debounceMs: 300,
      caseSensitive: !1,
      trimInput: !0,
      useWorker: !0
    };
  }
  // #region Internal State
  filters = /* @__PURE__ */ new Map();
  cachedResult = null;
  cacheKey = null;
  openPanelField = null;
  panelElement = null;
  panelAnchorElement = null;
  // For CSS anchor positioning cleanup
  searchText = /* @__PURE__ */ new Map();
  excludedValues = /* @__PURE__ */ new Map();
  panelAbortController = null;
  // For panel-scoped listeners
  globalStylesInjected = !1;
  // Virtualization constants for filter value list
  static LIST_ITEM_HEIGHT = 28;
  static LIST_OVERSCAN = 3;
  static LIST_BYPASS_THRESHOLD = 50;
  // Don't virtualize if < 50 items
  /**
   * Sync excludedValues map from a filter model (for set filters).
   */
  syncExcludedValues(e, t) {
    t ? t.type === "set" && t.operator === "notIn" && Array.isArray(t.value) ? this.excludedValues.set(e, new Set(t.value)) : t.type === "set" && this.excludedValues.delete(e) : this.excludedValues.delete(e);
  }
  // #endregion
  // #region Lifecycle
  attach(e) {
    super.attach(e), this.injectGlobalStyles();
  }
  detach() {
    this.filters.clear(), this.cachedResult = null, this.cacheKey = null, this.openPanelField = null, this.panelElement && (this.panelElement.remove(), this.panelElement = null), this.searchText.clear(), this.excludedValues.clear(), this.panelAbortController?.abort(), this.panelAbortController = null;
  }
  // #endregion
  // #region Hooks
  processRows(e) {
    const t = [...this.filters.values()];
    if (!t.length) return [...e];
    if (this.config.filterHandler)
      return this.cachedResult ? this.cachedResult : [...e];
    const r = Y(t);
    if (this.cacheKey === r && this.cachedResult)
      return this.cachedResult;
    const n = B([...e], t, this.config.caseSensitive);
    return this.cachedResult = n, this.cacheKey = r, n;
  }
  afterRender() {
    const e = this.gridElement;
    if (!e) return;
    e.querySelectorAll('[part~="header-cell"]').forEach((r) => {
      const n = r.getAttribute("data-col");
      if (n === null) return;
      const i = this.visibleColumns[parseInt(n, 10)];
      if (!i || i.filterable === !1 || z(i)) return;
      const l = i.field;
      if (!l) return;
      const a = this.filters.has(l);
      let o = r.querySelector(".tbw-filter-btn");
      if (o) {
        o.classList.toggle("active", a), r.classList.toggle("filtered", a);
        return;
      }
      o = document.createElement("button"), o.className = "tbw-filter-btn", o.setAttribute("aria-label", `Filter ${i.header ?? l}`), o.innerHTML = '<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>', a && (o.classList.add("active"), r.classList.add("filtered")), o.addEventListener("click", (b) => {
        b.stopPropagation(), this.toggleFilterPanel(l, i, o);
      });
      const p = r.querySelector(".resize-handle");
      p ? r.insertBefore(o, p) : r.appendChild(o);
    });
  }
  // #endregion
  // #region Public API
  /**
   * Set a filter on a specific field.
   * Pass null to remove the filter.
   */
  setFilter(e, t) {
    if (t === null)
      this.filters.delete(e), this.syncExcludedValues(e, null);
    else {
      const r = { ...t, field: e };
      this.filters.set(e, r), this.syncExcludedValues(e, r);
    }
    this.cachedResult = null, this.cacheKey = null, this.emit("filter-change", {
      filters: [...this.filters.values()],
      filteredRowCount: 0
      // Will be accurate after processRows
    }), this.requestRender();
  }
  /**
   * Get the current filter for a field.
   */
  getFilter(e) {
    return this.filters.get(e);
  }
  /**
   * Get all active filters.
   */
  getFilters() {
    return [...this.filters.values()];
  }
  /**
   * Alias for getFilters() to match functional API naming.
   */
  getFilterModel() {
    return this.getFilters();
  }
  /**
   * Set filters from an array (replaces all existing filters).
   */
  setFilterModel(e) {
    this.filters.clear(), this.excludedValues.clear();
    for (const t of e)
      this.filters.set(t.field, t), this.syncExcludedValues(t.field, t);
    this.cachedResult = null, this.cacheKey = null, this.emit("filter-change", {
      filters: [...this.filters.values()],
      filteredRowCount: 0
    }), this.requestRender();
  }
  /**
   * Clear all filters.
   */
  clearAllFilters() {
    this.filters.clear(), this.excludedValues.clear(), this.searchText.clear(), this.applyFiltersInternal();
  }
  /**
   * Clear filter for a specific field.
   */
  clearFieldFilter(e) {
    this.filters.delete(e), this.excludedValues.delete(e), this.searchText.delete(e), this.applyFiltersInternal();
  }
  /**
   * Check if a field has an active filter.
   */
  isFieldFiltered(e) {
    return this.filters.has(e);
  }
  /**
   * Get the count of filtered rows (from cache).
   */
  getFilteredRowCount() {
    return this.cachedResult?.length ?? this.rows.length;
  }
  /**
   * Get all active filters (alias for getFilters).
   */
  getActiveFilters() {
    return this.getFilters();
  }
  /**
   * Get unique values for a field (for set filter dropdowns).
   * Uses sourceRows to include all values regardless of current filter.
   */
  getUniqueValues(e) {
    return H(this.sourceRows, e);
  }
  // #endregion
  // #region Private Methods
  /**
   * Inject global styles for filter panel (rendered in document.body)
   */
  injectGlobalStyles() {
    if (this.globalStylesInjected) return;
    if (document.getElementById("tbw-filter-panel-styles")) {
      this.globalStylesInjected = !0;
      return;
    }
    const e = document.createElement("style");
    e.id = "tbw-filter-panel-styles", e.textContent = $, document.head.appendChild(e), this.globalStylesInjected = !0;
  }
  /**
   * Toggle the filter panel for a field
   */
  toggleFilterPanel(e, t, r) {
    if (this.openPanelField === e) {
      this.closeFilterPanel();
      return;
    }
    this.closeFilterPanel();
    const n = document.createElement("div");
    if (n.className = "tbw-filter-panel", this.isAnimationEnabled && n.classList.add("tbw-filter-panel-animated"), this.panelElement = n, this.openPanelField = e, this.config.valuesHandler) {
      n.innerHTML = '<div class="tbw-filter-loading">Loading...</div>', document.body.appendChild(n), this.positionPanel(n, r), this.setupPanelCloseHandler(n, r), this.config.valuesHandler(e, t).then((l) => {
        this.openPanelField !== e || !this.panelElement || (n.innerHTML = "", this.renderPanelContent(e, t, n, l));
      });
      return;
    }
    const i = H(this.sourceRows, e);
    this.renderPanelContent(e, t, n, i), document.body.appendChild(n), this.positionPanel(n, r), this.setupPanelCloseHandler(n, r);
  }
  /**
   * Render filter panel content with given values
   */
  renderPanelContent(e, t, r, n) {
    let i = this.excludedValues.get(e);
    i || (i = /* @__PURE__ */ new Set(), this.excludedValues.set(e, i));
    const l = this.searchText.get(e) ?? "", a = {
      field: e,
      column: t,
      uniqueValues: n,
      excludedValues: i,
      searchText: l,
      applySetFilter: (p) => {
        this.applySetFilter(e, p), this.closeFilterPanel();
      },
      applyTextFilter: (p, b, C) => {
        this.applyTextFilter(e, p, b, C), this.closeFilterPanel();
      },
      clearFilter: () => {
        this.clearFieldFilter(e), this.closeFilterPanel();
      },
      closePanel: () => this.closeFilterPanel()
    };
    let o = !1;
    this.config.filterPanelRenderer && (this.config.filterPanelRenderer(r, a), o = r.children.length > 0), o || this.renderDefaultFilterPanel(r, a, n, i);
  }
  /**
   * Setup click-outside handler to close the panel
   */
  setupPanelCloseHandler(e, t) {
    this.panelAbortController = new AbortController(), setTimeout(() => {
      document.addEventListener(
        "click",
        (r) => {
          !e.contains(r.target) && r.target !== t && this.closeFilterPanel();
        },
        { signal: this.panelAbortController?.signal }
      );
    }, 0);
  }
  /**
   * Close the filter panel
   */
  closeFilterPanel() {
    const e = this.panelElement;
    e && (e.remove(), this.panelElement = null), this.panelAnchorElement && (this.panelAnchorElement.style.anchorName = "", this.panelAnchorElement = null), this.openPanelField = null, this.panelAbortController?.abort(), this.panelAbortController = null;
  }
  /** Cache for CSS anchor positioning support check */
  static supportsAnchorPositioning = null;
  /**
   * Check if browser supports CSS Anchor Positioning
   */
  static checkAnchorPositioningSupport() {
    return g.supportsAnchorPositioning === null && (g.supportsAnchorPositioning = CSS.supports("anchor-name", "--test")), g.supportsAnchorPositioning;
  }
  /**
   * Position the panel below the header cell
   * Uses CSS Anchor Positioning if supported, falls back to JS positioning
   */
  positionPanel(e, t) {
    const n = t.closest(".cell") ?? t;
    if (n.style.anchorName = "--tbw-filter-anchor", this.panelAnchorElement = n, g.checkAnchorPositioningSupport()) {
      requestAnimationFrame(() => {
        const l = e.getBoundingClientRect(), a = n.getBoundingClientRect();
        l.top < a.top && e.classList.add("tbw-filter-panel-above");
      });
      return;
    }
    const i = n.getBoundingClientRect();
    e.style.position = "fixed", e.style.top = `${i.bottom + 4}px`, e.style.left = `${i.left}px`, requestAnimationFrame(() => {
      const l = e.getBoundingClientRect();
      l.right > window.innerWidth - 8 && (e.style.left = `${i.right - l.width}px`), l.bottom > window.innerHeight - 8 && (e.style.top = `${i.top - l.height - 4}px`, e.classList.add("tbw-filter-panel-above"));
    });
  }
  /**
   * Render the default filter panel content
   */
  renderDefaultFilterPanel(e, t, r, n) {
    const { field: i } = t, l = document.createElement("div");
    l.className = "tbw-filter-search";
    const a = document.createElement("input");
    a.type = "text", a.placeholder = "Search...", a.className = "tbw-filter-search-input", a.value = this.searchText.get(i) ?? "", l.appendChild(a), e.appendChild(l);
    const o = document.createElement("div");
    o.className = "tbw-filter-actions";
    const p = document.createElement("label");
    p.className = "tbw-filter-value-item", p.style.padding = "0", p.style.margin = "0";
    const b = document.createElement("input");
    b.type = "checkbox", b.className = "tbw-filter-checkbox";
    const C = document.createElement("span");
    C.textContent = "Select All", p.appendChild(b), p.appendChild(C), o.appendChild(p);
    const T = () => {
      const s = [...y.values()], u = s.every((c) => c), w = s.every((c) => !c);
      b.checked = u, b.indeterminate = !u && !w;
    };
    b.addEventListener("change", () => {
      const s = b.checked;
      for (const u of y.keys())
        y.set(u, s);
      T(), A();
    }), e.appendChild(o);
    const v = document.createElement("div");
    v.className = "tbw-filter-values";
    const E = document.createElement("div");
    E.className = "tbw-filter-values-spacer", v.appendChild(E);
    const m = document.createElement("div");
    m.className = "tbw-filter-values-content", v.appendChild(m);
    const y = /* @__PURE__ */ new Map();
    r.forEach((s) => {
      const u = s == null ? "__null__" : String(s);
      y.set(u, !n.has(s));
    }), T();
    let x = [];
    const F = (s, u) => {
      const w = s == null ? "(Blank)" : String(s), c = s == null ? "__null__" : String(s), d = document.createElement("label");
      d.className = "tbw-filter-value-item", d.style.position = "absolute", d.style.top = `${u * g.LIST_ITEM_HEIGHT}px`, d.style.left = "0", d.style.right = "0", d.style.height = `${g.LIST_ITEM_HEIGHT}px`, d.style.boxSizing = "border-box";
      const f = document.createElement("input");
      f.type = "checkbox", f.className = "tbw-filter-checkbox", f.checked = y.get(c) ?? !0, f.dataset.value = c, f.addEventListener("change", () => {
        y.set(c, f.checked), T();
      });
      const N = document.createElement("span");
      return N.textContent = w, d.appendChild(f), d.appendChild(N), d;
    }, A = () => {
      const s = x.length, u = v.clientHeight, w = v.scrollTop;
      if (E.style.height = `${s * g.LIST_ITEM_HEIGHT}px`, V(s, g.LIST_BYPASS_THRESHOLD / 3)) {
        m.innerHTML = "", m.style.transform = "translateY(0px)", x.forEach((d, f) => {
          m.appendChild(F(d, f));
        });
        return;
      }
      const c = P({
        totalRows: s,
        viewportHeight: u,
        scrollTop: w,
        rowHeight: g.LIST_ITEM_HEIGHT,
        overscan: g.LIST_OVERSCAN
      });
      m.style.transform = `translateY(${c.offsetY}px)`, m.innerHTML = "";
      for (let d = c.start; d < c.end; d++)
        m.appendChild(F(x[d], d - c.start));
    }, I = (s) => {
      const u = this.config.caseSensitive ?? !1, w = u ? s : s.toLowerCase();
      if (x = r.filter((c) => {
        const d = c == null ? "(Blank)" : String(c), f = u ? d : d.toLowerCase();
        return !s || f.includes(w);
      }), x.length === 0) {
        E.style.height = "0px", m.innerHTML = "";
        const c = document.createElement("div");
        c.className = "tbw-filter-no-match", c.textContent = "No matching values", m.appendChild(c);
        return;
      }
      A();
    };
    v.addEventListener(
      "scroll",
      () => {
        x.length > 0 && A();
      },
      { passive: !0 }
    ), I(a.value), e.appendChild(v);
    let L;
    a.addEventListener("input", () => {
      clearTimeout(L), L = setTimeout(() => {
        this.searchText.set(i, a.value), I(a.value);
      }, this.config.debounceMs ?? 150);
    });
    const S = document.createElement("div");
    S.className = "tbw-filter-buttons";
    const R = document.createElement("button");
    R.className = "tbw-filter-apply-btn", R.textContent = "Apply", R.addEventListener("click", () => {
      const s = [];
      for (const [u, w] of y)
        if (!w)
          if (u === "__null__")
            s.push(null);
          else {
            const c = r.find((d) => String(d) === u);
            s.push(c !== void 0 ? c : u);
          }
      t.applySetFilter(s);
    }), S.appendChild(R);
    const k = document.createElement("button");
    k.className = "tbw-filter-clear-btn", k.textContent = "Clear Filter", k.addEventListener("click", () => {
      t.clearFilter();
    }), S.appendChild(k), e.appendChild(S);
  }
  /**
   * Apply a set filter (exclude values)
   */
  applySetFilter(e, t) {
    this.excludedValues.set(e, new Set(t)), t.length === 0 ? this.filters.delete(e) : this.filters.set(e, {
      field: e,
      type: "set",
      operator: "notIn",
      value: t
    }), this.applyFiltersInternal();
  }
  /**
   * Apply a text filter
   */
  applyTextFilter(e, t, r, n) {
    this.filters.set(e, {
      field: e,
      type: "text",
      operator: t,
      value: r,
      valueTo: n
    }), this.applyFiltersInternal();
  }
  /**
   * Internal method to apply filters (sync or async based on config)
   */
  applyFiltersInternal() {
    this.cachedResult = null, this.cacheKey = null;
    const e = [...this.filters.values()];
    if (this.config.filterHandler) {
      const t = this.grid;
      t.setAttribute("aria-busy", "true");
      const r = this.config.filterHandler(e, this.sourceRows), n = (i) => {
        t.removeAttribute("aria-busy"), this.cachedResult = i, this.grid.rows = i, this.emit("filter-change", {
          filters: e,
          filteredRowCount: i.length
        }), this.requestRender();
      };
      r && typeof r.then == "function" ? r.then(n) : n(r);
      return;
    }
    this.emit("filter-change", {
      filters: e,
      filteredRowCount: 0
    }), this.requestRender();
  }
  // #endregion
  // #region Column State Hooks
  /**
   * Return filter state for a column if it has an active filter.
   */
  getColumnState(e) {
    const t = this.filters.get(e);
    if (t)
      return {
        filter: {
          type: t.type,
          operator: t.operator,
          value: t.value,
          valueTo: t.valueTo
        }
      };
  }
  /**
   * Apply filter state from column state.
   */
  applyColumnState(e, t) {
    if (!t.filter) {
      this.filters.delete(e);
      return;
    }
    const r = {
      field: e,
      type: t.filter.type,
      operator: t.filter.operator,
      value: t.filter.value,
      valueTo: t.filter.valueTo
    };
    this.filters.set(e, r), this.cachedResult = null, this.cacheKey = null;
  }
  // #endregion
}
export {
  g as FilteringPlugin
};
//# sourceMappingURL=index.js.map
