const p = {
  expand: "▶",
  collapse: "▼",
  sortAsc: "▲",
  sortDesc: "▼",
  sortNone: "⇅",
  submenuArrow: "▶",
  dragHandle: "⋮⋮",
  toolPanel: "☰"
};
class f {
  /** Plugin version - override in subclass if needed */
  version = "1.0.0";
  /** 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;
  /**
   * 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.
   */
  attach(e) {
    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.
   */
  detach() {
  }
  /**
   * Get another plugin instance from the same grid.
   * Use for inter-plugin communication.
   */
  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 }));
  }
  /**
   * Request a re-render of the grid.
   */
  requestRender() {
    this.grid?.requestRender?.();
  }
  /**
   * 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 shadow root of the grid.
   */
  get shadowRoot() {
    return this.grid?.shadowRoot ?? null;
  }
  /**
   * 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.grid?.disconnectSignal;
  }
  /**
   * Get the grid-level icons configuration.
   * Returns merged icons (user config + defaults).
   */
  get gridIcons() {
    const e = this.grid?.gridConfig?.icons ?? {};
    return { ...p, ...e };
  }
  /**
   * 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
}
const v = '.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:8px}.tbw-visibility-row{display:flex;align-items:center;gap:8px;padding:6px 4px;cursor:pointer;font-size:13px;border-radius:var(--tbw-border-radius, 4px);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover, #f3f4f6))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted, #888)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted, #888);font-size:10px;letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg, #1f2937)}.tbw-visibility-label{display:flex;align-items:center;gap:8px;flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent, #3b82f6))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent, #3b82f6))}.tbw-visibility-show-all{margin:8px;padding:8px 12px;border:1px solid var(--tbw-visibility-border, var(--tbw-color-border, #e5e7eb));border-radius:var(--tbw-border-radius, 4px);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg, #f9fafb));color:var(--tbw-color-fg, #1f2937);cursor:pointer;font-size:13px}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover, #f3f4f6))}';
function h(u) {
  const e = u.meta ?? {};
  return e.lockPosition !== !0 && e.suppressMovable !== !0;
}
class g extends f {
  name = "visibility";
  version = "1.0.0";
  /** Tool panel ID for shell integration */
  static PANEL_ID = "columns";
  get defaultConfig() {
    return {
      allowHideAll: !1
    };
  }
  // #region Internal State
  columnListElement = null;
  // Drag state for reorder integration
  isDragging = !1;
  draggedField = null;
  draggedIndex = null;
  dropIndex = null;
  // #endregion
  // #region Lifecycle
  detach() {
    this.columnListElement = null, this.isDragging = !1, this.draggedField = null, this.draggedIndex = null, this.dropIndex = null;
  }
  // #endregion
  // #region Shell Integration
  /**
   * Register the column visibility tool panel with the shell.
   */
  getToolPanel() {
    return {
      id: g.PANEL_ID,
      title: "Columns",
      icon: "☰",
      tooltip: "Column visibility",
      order: 100,
      // High order so it appears last
      render: (e) => this.renderPanelContent(e)
    };
  }
  // #endregion
  // #region Public API
  /**
   * Show the visibility sidebar panel.
   */
  show() {
    this.grid.openToolPanel(g.PANEL_ID);
  }
  /**
   * Hide the visibility sidebar panel.
   */
  hide() {
    this.grid.closeToolPanel();
  }
  /**
   * Toggle the visibility sidebar panel.
   */
  toggle() {
    this.grid.toggleToolPanel(g.PANEL_ID);
  }
  /**
   * Check if a specific column is visible.
   * Delegates to grid.isColumnVisible().
   * @param field - The field name to check
   * @returns True if the column is visible
   */
  isColumnVisible(e) {
    return this.grid.isColumnVisible(e);
  }
  /**
   * Set visibility for a specific column.
   * Delegates to grid.setColumnVisible().
   * @param field - The field name of the column
   * @param visible - Whether the column should be visible
   */
  setColumnVisible(e, t) {
    this.grid.setColumnVisible(e, t);
  }
  /**
   * Get list of all visible column fields.
   * @returns Array of visible field names
   */
  getVisibleColumns() {
    return this.grid.getAllColumns().filter((t) => t.visible).map((t) => t.field);
  }
  /**
   * Get list of all hidden column fields.
   * @returns Array of hidden field names
   */
  getHiddenColumns() {
    return this.grid.getAllColumns().filter((t) => !t.visible).map((t) => t.field);
  }
  /**
   * Show all columns.
   * Delegates to grid.showAllColumns().
   */
  showAll() {
    this.grid.showAllColumns();
  }
  /**
   * Toggle visibility for a specific column.
   * Delegates to grid.toggleColumnVisibility().
   * @param field - The field name of the column
   */
  toggleColumn(e) {
    this.grid.toggleColumnVisibility(e);
  }
  /**
   * Show a specific column.
   * Delegates to grid.setColumnVisible().
   * @param field - The field name of the column to show
   */
  showColumn(e) {
    this.grid.setColumnVisible(e, !0);
  }
  /**
   * Hide a specific column.
   * Delegates to grid.setColumnVisible().
   * @param field - The field name of the column to hide
   */
  hideColumn(e) {
    this.grid.setColumnVisible(e, !1);
  }
  /**
   * Get all columns with their visibility status.
   * Useful for building visibility UI.
   * @returns Array of column info with visibility status
   */
  getAllColumns() {
    return this.grid.getAllColumns();
  }
  /**
   * Check if the sidebar panel is currently open.
   * @returns True if the panel is open
   */
  isPanelVisible() {
    return this.grid.activeToolPanel === g.PANEL_ID;
  }
  // #endregion
  // #region Private Methods
  /**
   * Render the panel content into the shell's tool panel container.
   * Returns a cleanup function.
   */
  renderPanelContent(e) {
    const t = this.grid, l = document.createElement("div");
    l.className = "tbw-visibility-content";
    const o = document.createElement("div");
    o.className = "tbw-visibility-list", l.appendChild(o);
    const i = document.createElement("button");
    return i.className = "tbw-visibility-show-all", i.textContent = "Show All", i.addEventListener("click", () => {
      t.showAllColumns(), this.rebuildToggles(o);
    }), l.appendChild(i), this.columnListElement = o, this.rebuildToggles(o), e.appendChild(l), () => {
      this.columnListElement = null, l.remove();
    };
  }
  /**
   * Check if a reorder plugin is present (by name to avoid static import).
   */
  hasReorderPlugin() {
    const e = this.grid?.getPluginByName?.("reorder");
    return !!(e && typeof e.moveColumn == "function");
  }
  /**
   * Build the column toggle checkboxes.
   * When a reorder plugin is present, adds drag handles for reordering.
   */
  rebuildToggles(e) {
    const t = this.grid, l = this.hasReorderPlugin();
    e.innerHTML = "";
    const o = t.getAllColumns();
    for (let i = 0; i < o.length; i++) {
      const s = o[i], n = s.header || s.field, r = document.createElement("div");
      r.className = s.lockVisible ? "tbw-visibility-row locked" : "tbw-visibility-row", r.setAttribute("data-field", s.field), r.setAttribute("data-index", String(i)), l && h(s) && (r.draggable = !0, r.classList.add("reorderable"), this.setupDragListeners(r, s.field, i, e));
      const d = document.createElement("label");
      d.className = "tbw-visibility-label";
      const a = document.createElement("input");
      a.type = "checkbox", a.checked = s.visible, a.disabled = s.lockVisible ?? !1, a.addEventListener("change", () => {
        t.toggleColumnVisibility(s.field), setTimeout(() => this.rebuildToggles(e), 0);
      });
      const b = document.createElement("span");
      if (b.textContent = n, d.appendChild(a), d.appendChild(b), l && h(s)) {
        const c = document.createElement("span");
        c.className = "tbw-visibility-handle", this.setIcon(c, this.resolveIcon("dragHandle")), c.title = "Drag to reorder", r.appendChild(c);
      }
      r.appendChild(d), e.appendChild(r);
    }
  }
  /**
   * Set up drag-and-drop event listeners for a row.
   * On drop, emits a 'column-reorder-request' event for other plugins to handle.
   */
  setupDragListeners(e, t, l, o) {
    e.addEventListener("dragstart", (i) => {
      this.isDragging = !0, this.draggedField = t, this.draggedIndex = l, i.dataTransfer && (i.dataTransfer.effectAllowed = "move", i.dataTransfer.setData("text/plain", t)), e.classList.add("dragging");
    }), e.addEventListener("dragend", () => {
      this.isDragging = !1, this.draggedField = null, this.draggedIndex = null, this.dropIndex = null, o.querySelectorAll(".tbw-visibility-row").forEach((i) => {
        i.classList.remove("dragging", "drop-target", "drop-before", "drop-after");
      });
    }), e.addEventListener("dragover", (i) => {
      if (i.preventDefault(), !this.isDragging || this.draggedField === t) return;
      const s = e.getBoundingClientRect(), n = s.top + s.height / 2;
      this.dropIndex = i.clientY < n ? l : l + 1, o.querySelectorAll(".tbw-visibility-row").forEach((r) => {
        r !== e && r.classList.remove("drop-target", "drop-before", "drop-after");
      }), e.classList.add("drop-target"), e.classList.toggle("drop-before", i.clientY < n), e.classList.toggle("drop-after", i.clientY >= n);
    }), e.addEventListener("dragleave", () => {
      e.classList.remove("drop-target", "drop-before", "drop-after");
    }), e.addEventListener("drop", (i) => {
      i.preventDefault();
      const s = this.draggedField, n = this.draggedIndex, r = this.dropIndex;
      if (!this.isDragging || s === null || n === null || r === null)
        return;
      const d = r > n ? r - 1 : r;
      if (d !== n) {
        const a = {
          field: s,
          fromIndex: n,
          toIndex: d
        };
        this.emit("column-reorder-request", a), setTimeout(() => {
          this.rebuildToggles(o);
        }, 0);
      }
    });
  }
  // #endregion
  // #region Styles
  styles = v;
  // #endregion
}
export {
  g as VisibilityPlugin
};
//# sourceMappingURL=index.js.map
