const b = {
  expand: "▶",
  collapse: "▼",
  sortAsc: "▲",
  sortDesc: "▼",
  sortNone: "⇅",
  submenuArrow: "▶",
  dragHandle: "⋮⋮",
  toolPanel: "☰"
};
class w {
  /** 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(t = {}) {
    this.userConfig = t;
  }
  /**
   * Called when the plugin is attached to a grid.
   * Override to set up event listeners, initialize state, etc.
   */
  attach(t) {
    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.
   */
  detach() {
  }
  /**
   * Get another plugin instance from the same grid.
   * Use for inter-plugin communication.
   */
  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 }));
  }
  /**
   * 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 t = this.grid?.gridConfig?.icons ?? {};
    return { ...b, ...t };
  }
  /**
   * 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 m(i, t = !0) {
  if (i == null) return "";
  if (i instanceof Date) return i.toISOString();
  if (typeof i == "object") return JSON.stringify(i);
  const e = String(i);
  return t && (e.includes(",") || e.includes('"') || e.includes(`
`) || e.includes("\r")) ? `"${e.replace(/"/g, '""')}"` : e;
}
function C(i, t, e, s = {}) {
  const c = s.delimiter ?? ",", l = s.newline ?? `
`, o = [], r = s.bom ? "\uFEFF" : "";
  if (e.includeHeaders !== !1) {
    const n = t.map((u) => {
      const d = u.header || u.field, f = e.processHeader ? e.processHeader(d, u.field) : d;
      return m(f);
    });
    o.push(n.join(c));
  }
  for (const n of i) {
    const u = t.map((d) => {
      let f = n[d.field];
      return e.processCell && (f = e.processCell(f, d.field, n)), m(f);
    });
    o.push(u.join(c));
  }
  return r + o.join(l);
}
function h(i, t) {
  const e = URL.createObjectURL(i), s = document.createElement("a");
  s.href = e, s.download = t, s.style.display = "none", document.body.appendChild(s), s.click(), document.body.removeChild(s), URL.revokeObjectURL(e);
}
function S(i, t) {
  const e = new Blob([i], { type: "text/csv;charset=utf-8;" });
  h(e, t);
}
function x(i) {
  return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
function E(i, t, e) {
  let s = `<?xml version="1.0" encoding="UTF-8"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
<Worksheet ss:Name="Sheet1">
<Table>`;
  if (e.includeHeaders !== !1) {
    s += `
<Row>`;
    for (const c of t) {
      const l = c.header || c.field, o = e.processHeader ? e.processHeader(l, c.field) : l;
      s += `<Cell><Data ss:Type="String">${x(o)}</Data></Cell>`;
    }
    s += "</Row>";
  }
  for (const c of i) {
    s += `
<Row>`;
    for (const l of t) {
      let o = c[l.field];
      e.processCell && (o = e.processCell(o, l.field, c));
      let r = "String", n = "";
      o == null ? n = "" : typeof o == "number" && !isNaN(o) ? (r = "Number", n = String(o)) : o instanceof Date ? (r = "DateTime", n = o.toISOString()) : n = x(String(o)), s += `<Cell><Data ss:Type="${r}">${n}</Data></Cell>`;
    }
    s += "</Row>";
  }
  return s += `
</Table>
</Worksheet>
</Workbook>`, s;
}
function y(i, t) {
  const e = t.endsWith(".xls") ? t : `${t}.xls`, s = new Blob([i], {
    type: "application/vnd.ms-excel;charset=utf-8;"
  });
  h(s, e);
}
class R extends w {
  name = "export";
  version = "1.0.0";
  get defaultConfig() {
    return {
      fileName: "export",
      includeHeaders: !0,
      onlyVisible: !0,
      onlySelected: !1
    };
  }
  // #region Internal State
  isExportingFlag = !1;
  lastExportInfo = null;
  // #endregion
  // #region Private Methods
  performExport(t, e) {
    const s = this.config, c = {
      format: t,
      fileName: e?.fileName ?? s.fileName ?? "export",
      includeHeaders: e?.includeHeaders ?? s.includeHeaders,
      processCell: e?.processCell,
      processHeader: e?.processHeader,
      columns: e?.columns,
      rowIndices: e?.rowIndices
    };
    let l = [...this.columns];
    if (s.onlyVisible && (l = l.filter((n) => !n.hidden && !n.field.startsWith("__"))), e?.columns) {
      const n = new Set(e.columns);
      l = l.filter((u) => n.has(u.field));
    }
    let o = [...this.rows];
    if (s.onlySelected) {
      const n = this.getSelectionState();
      n?.selected?.size && (o = [...n.selected].sort((d, f) => d - f).map((d) => this.rows[d]).filter(Boolean));
    }
    e?.rowIndices && (o = e.rowIndices.map((n) => this.rows[n]).filter(Boolean)), this.isExportingFlag = !0;
    let r = c.fileName;
    try {
      switch (t) {
        case "csv": {
          const n = C(o, l, c, { bom: !0 });
          r = r.endsWith(".csv") ? r : `${r}.csv`, S(n, r);
          break;
        }
        case "excel": {
          const n = E(o, l, c);
          r = r.endsWith(".xls") ? r : `${r}.xls`, y(n, r);
          break;
        }
        case "json": {
          const n = o.map((f) => {
            const p = {};
            for (const a of l) {
              let g = f[a.field];
              c.processCell && (g = c.processCell(g, a.field, f)), p[a.field] = g;
            }
            return p;
          }), u = JSON.stringify(n, null, 2);
          r = r.endsWith(".json") ? r : `${r}.json`;
          const d = new Blob([u], { type: "application/json" });
          h(d, r);
          break;
        }
      }
      this.lastExportInfo = { format: t, timestamp: /* @__PURE__ */ new Date() }, this.emit("export-complete", {
        format: t,
        fileName: r,
        rowCount: o.length,
        columnCount: l.length
      });
    } finally {
      this.isExportingFlag = !1;
    }
  }
  getSelectionState() {
    try {
      return this.grid?.getPluginState?.("selection") ?? null;
    } catch {
      return null;
    }
  }
  // #endregion
  // #region Public API
  /**
   * Export data to CSV format.
   * @param params - Optional export parameters
   */
  exportCsv(t) {
    this.performExport("csv", t);
  }
  /**
   * Export data to Excel format (XML Spreadsheet).
   * @param params - Optional export parameters
   */
  exportExcel(t) {
    this.performExport("excel", t);
  }
  /**
   * Export data to JSON format.
   * @param params - Optional export parameters
   */
  exportJson(t) {
    this.performExport("json", t);
  }
  /**
   * Check if an export is currently in progress.
   * @returns Whether export is in progress
   */
  isExporting() {
    return this.isExportingFlag;
  }
  /**
   * Get information about the last export.
   * @returns Export info or null if no export has occurred
   */
  getLastExport() {
    return this.lastExportInfo;
  }
  // #endregion
}
export {
  R as ExportPlugin
};
//# sourceMappingURL=index.js.map
