const C = {
  expand: "▶",
  collapse: "▼",
  sortAsc: "▲",
  sortDesc: "▼",
  sortNone: "⇅",
  submenuArrow: "▶",
  dragHandle: "⋮⋮",
  toolPanel: "☰"
};
class I {
  /**
   * 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 n = new CustomEvent(e, { detail: t, bubbles: !0, cancelable: !0 });
    return this.grid?.dispatchEvent?.(n), n.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 { ...C, ...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(), n = parseInt(t, 10);
      if (!isNaN(n)) return n;
    }
    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
}
const g = "@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg, light-dark(#f5f5f5, #2a2a2a)));color:var(--tbw-context-menu-fg, var(--tbw-color-fg, light-dark(#222, #eee)));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-border-radius, .25rem);box-shadow:0 2px 10px var(--tbw-color-shadow, rgba(0, 0, 0, .15));min-width:var(--tbw-menu-min-width, 10rem);padding:var(--tbw-spacing-xs, .25rem) 0;z-index:10000;font-size:var(--tbw-font-size-sm, .8125rem);font-family:var(--tbw-font-family, system-ui, sans-serif)}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .75rem);cursor:pointer;gap:var(--tbw-menu-item-gap, .5rem)}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover, light-dark(#e8e8e8, #3a3a3a)))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:light-dark(#c00,#f66)}.tbw-context-menu-icon{width:var(--tbw-icon-size, 1rem);text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut{color:var(--tbw-color-fg-muted, light-dark(#888, #888));font-size:var(--tbw-font-size-xs, .6875rem)}.tbw-context-menu-arrow{font-size:var(--tbw-font-size-2xs, .625rem);color:var(--tbw-color-fg-muted, light-dark(#888, #888))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));margin:var(--tbw-spacing-xs, .25rem) 0}}";
function v(r, e) {
  return (typeof r == "function" ? r(e) : r).filter((n) => !(n.hidden === !0 || typeof n.hidden == "function" && n.hidden(e)));
}
function M(r, e) {
  return r.disabled === !0 ? !0 : typeof r.disabled == "function" ? r.disabled(e) : !1;
}
function x(r, e, t, n = C.submenuArrow) {
  const l = document.createElement("div");
  l.className = "tbw-context-menu", l.setAttribute("role", "menu");
  for (const o of r) {
    if (o.separator) {
      const s = document.createElement("div");
      s.className = "tbw-context-menu-separator", s.setAttribute("role", "separator"), l.appendChild(s);
      continue;
    }
    const i = document.createElement("div");
    i.className = "tbw-context-menu-item", o.cssClass && i.classList.add(o.cssClass), i.setAttribute("role", "menuitem"), i.setAttribute("data-id", o.id);
    const d = M(o, e);
    if (d && (i.classList.add("disabled"), i.setAttribute("aria-disabled", "true")), o.icon) {
      const s = document.createElement("span");
      s.className = "tbw-context-menu-icon", s.innerHTML = o.icon, i.appendChild(s);
    }
    const a = document.createElement("span");
    if (a.className = "tbw-context-menu-label", a.textContent = o.name, i.appendChild(a), o.shortcut) {
      const s = document.createElement("span");
      s.className = "tbw-context-menu-shortcut", s.textContent = o.shortcut, i.appendChild(s);
    }
    if (o.subMenu?.length) {
      const s = document.createElement("span");
      s.className = "tbw-context-menu-arrow", typeof n == "string" ? s.innerHTML = n : n instanceof HTMLElement && s.appendChild(n.cloneNode(!0)), i.appendChild(s), i.addEventListener("mouseenter", () => {
        if (i.querySelector(".tbw-context-menu") || !o.subMenu) return;
        const h = v(o.subMenu, e), c = x(h, e, t, n);
        c.classList.add("tbw-context-submenu"), c.style.position = "absolute", c.style.left = "100%", c.style.top = "0", i.style.position = "relative", i.appendChild(c);
      }), i.addEventListener("mouseleave", () => {
        const u = i.querySelector(".tbw-context-menu");
        u && u.remove();
      });
    }
    !d && o.action && !o.subMenu && i.addEventListener("click", (s) => {
      s.stopPropagation(), t(o);
    }), l.appendChild(i);
  }
  return l;
}
function y(r, e, t) {
  r.style.position = "fixed", r.style.left = `${e}px`, r.style.top = `${t}px`, r.style.visibility = "hidden", r.style.zIndex = "10000";
  const n = r.getBoundingClientRect(), l = window.innerWidth, o = window.innerHeight;
  let i = e, d = t;
  e + n.width > l && (i = e - n.width), t + n.height > o && (d = t - n.height), i = Math.max(0, i), d = Math.max(0, d), r.style.left = `${i}px`, r.style.top = `${d}px`, r.style.visibility = "visible";
}
let f = null, b = null, m = null, p = 0;
const w = [
  {
    id: "copy",
    name: "Copy",
    shortcut: "Ctrl+C",
    action: (r) => {
      r.grid?.plugins?.clipboard?.copy?.();
    }
  },
  { separator: !0, id: "sep1", name: "" },
  {
    id: "export-csv",
    name: "Export CSV",
    action: (r) => {
      r.grid?.plugins?.export?.exportCsv?.();
    }
  }
];
class H extends I {
  name = "contextMenu";
  get defaultConfig() {
    return {
      items: w
    };
  }
  // #region Internal State
  isOpen = !1;
  position = { x: 0, y: 0 };
  params = null;
  menuElement = null;
  // #endregion
  // #region Lifecycle
  attach(e) {
    super.attach(e), this.installGlobalHandlers(), p++;
  }
  detach() {
    this.menuElement && (this.menuElement.remove(), this.menuElement = null), this.isOpen = !1, this.params = null, this.uninstallGlobalHandlers();
  }
  // #endregion
  // #region Private Methods
  installGlobalHandlers() {
    !m && typeof document < "u" && typeof g == "string" && g && (m = document.createElement("style"), m.id = "tbw-context-menu-styles", m.textContent = g, document.head.appendChild(m)), f || (f = () => {
      document.querySelectorAll(".tbw-context-menu").forEach((t) => t.remove());
    }, document.addEventListener("click", f)), b || (b = (e) => {
      e.key === "Escape" && document.querySelectorAll(".tbw-context-menu").forEach((n) => n.remove());
    }, document.addEventListener("keydown", b));
  }
  /**
   * Clean up global handlers when the last instance detaches.
   * Uses reference counting to ensure handlers persist while any grid uses the plugin.
   */
  uninstallGlobalHandlers() {
    p--, !(p > 0) && (f && (document.removeEventListener("click", f), f = null), b && (document.removeEventListener("keydown", b), b = null), m && (m.remove(), m = null));
  }
  // #endregion
  // #region Hooks
  afterRender() {
    const e = this.gridElement;
    if (!e) return;
    const t = e.children[0];
    t && t.getAttribute("data-context-menu-bound") !== "true" && (t.setAttribute("data-context-menu-bound", "true"), t.addEventListener("contextmenu", (n) => {
      const l = n;
      l.preventDefault();
      const o = l.target, i = o.closest("[data-row][data-col]"), d = o.closest(".header-cell");
      let a;
      if (i) {
        const u = parseInt(i.getAttribute("data-row") ?? "-1", 10), h = parseInt(i.getAttribute("data-col") ?? "-1", 10), c = this.columns[h], E = this.rows[u];
        a = {
          row: E,
          rowIndex: u,
          column: c,
          columnIndex: h,
          field: c?.field ?? "",
          value: E?.[c?.field] ?? null,
          isHeader: !1,
          event: l
        };
      } else if (d) {
        const u = parseInt(d.getAttribute("data-col") ?? "-1", 10), h = this.columns[u];
        a = {
          row: null,
          rowIndex: -1,
          column: h,
          columnIndex: u,
          field: h?.field ?? "",
          value: null,
          isHeader: !0,
          event: l
        };
      } else
        return;
      this.params = a, this.position = { x: l.clientX, y: l.clientY };
      const s = v(this.config.items ?? w, a);
      s.length && (this.menuElement && this.menuElement.remove(), this.menuElement = x(
        s,
        a,
        (u) => {
          u.action && u.action(a), this.menuElement?.remove(), this.menuElement = null, this.isOpen = !1;
        },
        this.gridIcons.submenuArrow
      ), document.body.appendChild(this.menuElement), y(this.menuElement, l.clientX, l.clientY), this.isOpen = !0, this.emit("context-menu-open", { params: a, items: s }));
    }));
  }
  // #endregion
  // #region Public API
  /**
   * Programmatically show the context menu at the specified position.
   * @param x - X coordinate
   * @param y - Y coordinate
   * @param params - Partial context menu parameters
   */
  showMenu(e, t, n) {
    const l = {
      row: n.row ?? null,
      rowIndex: n.rowIndex ?? -1,
      column: n.column ?? null,
      columnIndex: n.columnIndex ?? -1,
      field: n.field ?? "",
      value: n.value ?? null,
      isHeader: n.isHeader ?? !1,
      event: n.event ?? new MouseEvent("contextmenu")
    }, o = v(this.config.items ?? w, l);
    this.menuElement && this.menuElement.remove(), this.menuElement = x(
      o,
      l,
      (i) => {
        i.action && i.action(l), this.menuElement?.remove(), this.menuElement = null, this.isOpen = !1;
      },
      this.gridIcons.submenuArrow
    ), document.body.appendChild(this.menuElement), y(this.menuElement, e, t), this.isOpen = !0;
  }
  /**
   * Hide the context menu.
   */
  hideMenu() {
    this.menuElement && (this.menuElement.remove(), this.menuElement = null, this.isOpen = !1);
  }
  /**
   * Check if the context menu is currently open.
   * @returns Whether the menu is open
   */
  isMenuOpen() {
    return this.isOpen;
  }
  // #endregion
  // Styles are injected globally via installGlobalHandlers() since menu renders in document.body
}
export {
  H as ContextMenuPlugin
};
//# sourceMappingURL=index.js.map
