const d = '<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>', g = {
  expand: "▶",
  collapse: "▼",
  sortAsc: "▲",
  sortDesc: "▼",
  sortNone: "⇅",
  submenuArrow: "▶",
  dragHandle: "⋮⋮",
  toolPanel: "☰",
  filter: d,
  filterActive: d,
  print: "🖨️"
}, y = {
  /** Ask if a column can be moved. Context: ColumnConfig. Response: boolean | undefined */
  CAN_MOVE_COLUMN: "canMoveColumn"
};
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 manifest - declares owned properties, config rules, and hook priorities.
   *
   * This is read by the configuration validator to:
   * - Validate that required plugins are loaded when their properties are used
   * - Execute configRules to detect invalid/conflicting settings
   * - Order hook execution based on priority
   *
   * @example
   * ```typescript
   * static override readonly manifest: PluginManifest<MyConfig> = {
   *   ownedProperties: [
   *     { property: 'myProp', level: 'column', description: 'the "myProp" column property' },
   *   ],
   *   configRules: [
   *     { id: 'myPlugin/conflict', severity: 'warn', message: '...', check: (c) => c.a && c.b },
   *   ],
   * };
   * ```
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  static manifest;
  /**
   * 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.
   */
  #t;
  /**
   * 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(t = {}) {
    this.userConfig = t;
  }
  /**
   * 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(t) {
    this.#t?.abort(), this.#t = new AbortController(), this.grid = t, 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.#t?.abort(), this.#t = 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(t) {
    return this.grid?.getPlugin(t);
  }
  /**
   * Emit a custom event from the grid.
   */
  emit(t, e) {
    this.grid?.dispatchEvent?.(new CustomEvent(t, { detail: e, bubbles: !0 }));
  }
  /**
   * Emit a cancelable custom event from the grid.
   * @returns `true` if the event was cancelled (preventDefault called), `false` otherwise
   */
  emitCancelable(t, e) {
    const s = new CustomEvent(t, { detail: e, bubbles: !0, cancelable: !0 });
    return this.grid?.dispatchEvent?.(s), s.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 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.#t?.signal ?? this.grid?.disconnectSignal;
  }
  /**
   * Get the grid-level icons configuration.
   * Returns merged icons (user config + defaults).
   */
  get gridIcons() {
    const t = this.grid?.gridConfig?.icons ?? {};
    return { ...g, ...t };
  }
  // #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 t = this.grid?.effectiveConfig?.animation?.mode ?? "reduced-motion";
    if (t === !1 || t === "off") return !1;
    if (t === !0 || t === "on") return !0;
    const e = this.gridElement;
    return e ? getComputedStyle(e).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 t = this.gridElement;
    if (t) {
      const e = getComputedStyle(t).getPropertyValue("--tbw-animation-duration").trim(), s = parseInt(e, 10);
      if (!isNaN(s)) return s;
    }
    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(t, e) {
    return e !== void 0 ? e : this.gridIcons[t];
  }
  /**
   * 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(t, e) {
    typeof e == "string" ? t.innerHTML = e : e instanceof HTMLElement && (t.innerHTML = "", t.appendChild(e.cloneNode(!0)));
  }
  /**
   * Log a warning message.
   */
  warn(t) {
    console.warn(`[tbw-grid:${this.name}] ${t}`);
  }
  // #endregion
}
function p(r) {
  return r.filter((t) => t.sticky === "left");
}
function k(r) {
  return r.filter((t) => t.sticky === "right");
}
function a(r) {
  return r.some((t) => t.sticky === "left" || t.sticky === "right");
}
function u(r, t) {
  const e = Array.from(r.querySelectorAll(".header-row .cell"));
  if (!e.length) return;
  const s = /* @__PURE__ */ new Map();
  t.forEach((n, c) => {
    n.field && s.set(n.field, c);
  });
  let l = 0;
  for (const n of t)
    if (n.sticky === "left") {
      const c = s.get(n.field), i = e.find((o) => o.getAttribute("data-field") === n.field);
      i && (i.classList.add("sticky-left"), i.style.position = "sticky", i.style.left = l + "px", c !== void 0 && r.querySelectorAll(`.data-grid-row .cell[data-col="${c}"]`).forEach((o) => {
        o.classList.add("sticky-left"), o.style.position = "sticky", o.style.left = l + "px";
      }), l += i.offsetWidth);
    }
  let f = 0;
  for (const n of [...t].reverse())
    if (n.sticky === "right") {
      const c = s.get(n.field), i = e.find((o) => o.getAttribute("data-field") === n.field);
      i && (i.classList.add("sticky-right"), i.style.position = "sticky", i.style.right = f + "px", c !== void 0 && r.querySelectorAll(`.data-grid-row .cell[data-col="${c}"]`).forEach((o) => {
        o.classList.add("sticky-right"), o.style.position = "sticky", o.style.right = f + "px";
      }), f += i.offsetWidth);
    }
}
function h(r) {
  r.querySelectorAll(".sticky-left, .sticky-right").forEach((e) => {
    e.classList.remove("sticky-left", "sticky-right"), e.style.position = "", e.style.left = "", e.style.right = "";
  });
}
class C extends m {
  /**
   * Plugin manifest - declares owned properties for configuration validation.
   * @internal
   */
  static manifest = {
    ownedProperties: [
      {
        property: "sticky",
        level: "column",
        description: 'the "sticky" column property',
        isUsed: (t) => t === "left" || t === "right"
      }
    ]
  };
  /** @internal */
  name = "pinnedColumns";
  /** @internal */
  get defaultConfig() {
    return {};
  }
  // #region Internal State
  isApplied = !1;
  leftOffsets = /* @__PURE__ */ new Map();
  rightOffsets = /* @__PURE__ */ new Map();
  // #endregion
  // #region Lifecycle
  /** @internal */
  detach() {
    this.leftOffsets.clear(), this.rightOffsets.clear(), this.isApplied = !1;
  }
  // #endregion
  // #region Detection
  /**
   * Auto-detect sticky columns from column configuration.
   */
  static detect(t, e) {
    const s = e?.columns;
    return Array.isArray(s) ? a(s) : !1;
  }
  // #endregion
  // #region Hooks
  /** @internal */
  processColumns(t) {
    return this.isApplied = a([...t]), [...t];
  }
  /** @internal */
  afterRender() {
    if (!this.isApplied)
      return;
    const t = this.grid, e = [...this.columns];
    if (!a(e)) {
      h(t), this.isApplied = !1;
      return;
    }
    queueMicrotask(() => {
      u(t, e);
    });
  }
  /**
   * Handle inter-plugin queries.
   * @internal
   */
  onPluginQuery(t) {
    switch (t.type) {
      case y.CAN_MOVE_COLUMN: {
        const e = t.context, s = e.sticky;
        if (s === "left" || s === "right")
          return !1;
        const l = e.meta?.sticky;
        return l === "left" || l === "right" ? !1 : void 0;
      }
      default:
        return;
    }
  }
  // #endregion
  // #region Public API
  /**
   * Re-apply sticky offsets (e.g., after column resize).
   */
  refreshStickyOffsets() {
    const t = [...this.columns];
    u(this.grid, t);
  }
  /**
   * Get columns pinned to the left.
   */
  getLeftPinnedColumns() {
    const t = [...this.columns];
    return p(t);
  }
  /**
   * Get columns pinned to the right.
   */
  getRightPinnedColumns() {
    const t = [...this.columns];
    return k(t);
  }
  /**
   * Clear all sticky positioning.
   */
  clearStickyPositions() {
    h(this.grid);
  }
  /**
   * Report horizontal scroll boundary offsets for pinned columns.
   * Used by keyboard navigation to ensure focused cells aren't hidden behind sticky columns.
   * @internal
   */
  getHorizontalScrollOffsets(t, e) {
    if (!this.isApplied)
      return;
    let s = 0, l = 0;
    if (t) {
      const n = t.querySelectorAll(".sticky-left"), c = t.querySelectorAll(".sticky-right");
      n.forEach((i) => {
        s += i.offsetWidth;
      }), c.forEach((i) => {
        l += i.offsetWidth;
      });
    } else
      this.grid.querySelectorAll(".header-row .cell").forEach((i) => {
        i.classList.contains("sticky-left") ? s += i.offsetWidth : i.classList.contains("sticky-right") && (l += i.offsetWidth);
      });
    const f = e?.classList.contains("sticky-left") || e?.classList.contains("sticky-right");
    return { left: s, right: l, skipScroll: f };
  }
  // #endregion
}
export {
  C as PinnedColumnsPlugin
};
//# sourceMappingURL=index.js.map
