import {
  __decorateClass,
  __privateAdd,
  __privateGet,
  __privateMethod,
  __privateSet
} from "../../chunks/chunk.QU3DSPNU.js";
var _cache, _cacheDuration, _templateCache, _GdsTable_instances, Density_get, hasSelection_get, isAllSelected_get, isPartialSelection_get, getCacheKey_fn, isCacheValid_fn, loadData_fn, getSlotContent_fn, renderCell_fn, renderCellContent_fn, renderSortIcon_fn, hasHeaderContent_fn, renderHeaderControls_fn, renderColumnHeader_fn, renderActionsHeader_fn, renderSelectableHeader_fn, renderColumnHeaders_fn, renderTableHeader_fn, renderTableCell_fn, renderSelectableCell_fn, renderRowCells_fn, renderActionsCell_fn, renderTableRow_fn, renderCheckbox_fn, renderSkeletonCell_fn, renderSkeletonRow_fn, renderTableBody_fn, renderTable_fn, renderErrorState_fn, renderEmptyState_fn, renderFooter_fn, renderHeadline_fn, handleSearch_fn, handleSearchClear_fn, handleSort_fn, handlePageChange_fn, handlePageSizeChange_fn, handleColumnVisibility_fn, handleSelectAll_fn, handleRowSelect_fn, selectAllInternal_fn, clearSelectionInternal_fn, emitSelectionChange_fn, initializeScrollTracking_fn, updateVerticalScrollState_fn, updateHorizontalScrollState_fn;
import { localized, msg } from "@lit/localize";
import { property, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { ifDefined } from "lit/directives/if-defined.js";
import { styleMap } from "lit/directives/style-map.js";
import { when } from "lit/directives/when.js";
import { GdsElement } from "../../gds-element.js";
import { watchMediaQuery } from "../../utils/decorators/index.js";
import { styleExpressionProperty } from "../../utils/decorators/style-expression-property.js";
import { watch } from "../../utils/decorators/watch.js";
import { forSpaceTokensAndCustomValues } from "../../utils/helpers/index.js";
import {
  gdsCustomElement,
  html
} from "../../utils/helpers/custom-element-scoping.js";
import * as Table from "./table.imports.js";
import * as Types from "./table.types.js";
let GdsTable = class extends GdsElement {
  constructor() {
    super(...arguments);
    __privateAdd(this, _GdsTable_instances);
    __privateAdd(this, _cache, {});
    __privateAdd(this, _cacheDuration, 5 * 60 * 1e3);
    __privateAdd(this, _templateCache, /* @__PURE__ */ new Map());
    this.headlineTag = "h2";
    this.options = [5, 10, 20, 50, 100];
    this.page = 1;
    this.rows = 10;
    this.columns = [];
    this.density = "comfortable";
    this.selectable = false;
    this.responsive = false;
    this.plain = false;
    this.searchable = false;
    this.settings = false;
    this.striped = false;
    this.nocache = false;
    this.variant = "secondary";
    this._isMobile = false;
    this._view = {
      page: this.page,
      rows: this.rows,
      searchQuery: "",
      visibleColumns: /* @__PURE__ */ new Set()
    };
    this._loaded = true;
    this._loading = false;
    this._rowsState = [];
    this._total = 0;
    this._selected = /* @__PURE__ */ new Set();
    this._error = null;
  }
  _handleMobile(matches) {
    this._isMobile = matches;
  }
  _onDataChange() {
    __privateSet(this, _cache, {});
    __privateMethod(this, _GdsTable_instances, loadData_fn).call(this);
  }
  _onColumnsChange() {
    __privateSet(this, _cache, {});
    this._view = {
      ...this._view,
      page: Number(this.page ?? 1),
      rows: Number(this.rows ?? 10),
      visibleColumns: new Set(
        this.columns.filter((col) => col.visible !== false).map((col) => col.key)
      )
    };
  }
  connectedCallback() {
    super.connectedCallback();
    this.updateComplete.then(() => {
      __privateMethod(this, _GdsTable_instances, initializeScrollTracking_fn).call(this);
    });
  }
  render() {
    const classes = {
      table: true,
      plain: this.plain,
      striped: this.striped,
      [this.density]: this.density
    };
    return html`
      <div class="${classMap(classes)}">
        ${[
      __privateMethod(this, _GdsTable_instances, renderHeadline_fn).call(this),
      __privateMethod(this, _GdsTable_instances, renderHeaderControls_fn).call(this),
      when(
        this._error,
        () => __privateMethod(this, _GdsTable_instances, renderErrorState_fn).call(this),
        () => when(
          this._rowsState.length === 0 && !this._loading,
          () => __privateMethod(this, _GdsTable_instances, renderEmptyState_fn).call(this),
          () => __privateMethod(this, _GdsTable_instances, renderTable_fn).call(this)
        )
      ),
      __privateMethod(this, _GdsTable_instances, renderFooter_fn).call(this)
    ]}
      </div>
    `;
  }
  /**
   * Public API
   * Clear all selections
   */
  clearSelection() {
    __privateMethod(this, _GdsTable_instances, clearSelectionInternal_fn).call(this);
    __privateMethod(this, _GdsTable_instances, emitSelectionChange_fn).call(this);
  }
  /**
   * Select all rows
   */
  selectAll() {
    __privateMethod(this, _GdsTable_instances, selectAllInternal_fn).call(this);
    __privateMethod(this, _GdsTable_instances, emitSelectionChange_fn).call(this);
  }
  /**
   * Select specific rows by indices
   */
  setSelection(indices) {
    const validIndices = indices.filter(
      (i) => i >= 0 && i < this._rowsState.length
    );
    this._selected = new Set(validIndices);
    __privateMethod(this, _GdsTable_instances, emitSelectionChange_fn).call(this);
    this.requestUpdate();
  }
  /**
   * Get selected row data
   */
  getSelection() {
    const indices = Array.from(this._selected);
    return {
      indices,
      data: indices.map((i) => this._rowsState[i])
    };
  }
};
_cache = new WeakMap();
_cacheDuration = new WeakMap();
_templateCache = new WeakMap();
_GdsTable_instances = new WeakSet();
Density_get = function() {
  return Types.DENSITY_CONFIG[this.density];
};
hasSelection_get = function() {
  return this._selected.size > 0;
};
isAllSelected_get = function() {
  return this._rowsState.length > 0 && this._selected.size === this._rowsState.length;
};
isPartialSelection_get = function() {
  return __privateGet(this, _GdsTable_instances, hasSelection_get) && !__privateGet(this, _GdsTable_instances, isAllSelected_get);
};
getCacheKey_fn = function() {
  return JSON.stringify({
    page: this._view.page,
    rows: this._view.rows,
    sortColumn: this._view.sortColumn,
    sortDirection: this._view.sortDirection,
    searchQuery: this._view.searchQuery
  });
};
isCacheValid_fn = function(entry) {
  return Date.now() - entry.timestamp < __privateGet(this, _cacheDuration);
};
loadData_fn = async function() {
  if (!this.data) return;
  if (!this.nocache) {
    const cacheKey = __privateMethod(this, _GdsTable_instances, getCacheKey_fn).call(this);
    const cachedData = __privateGet(this, _cache)[cacheKey];
    if (cachedData && __privateMethod(this, _GdsTable_instances, isCacheValid_fn).call(this, cachedData)) {
      this._rowsState = cachedData.rows;
      this._total = cachedData.total;
      this._loaded = false;
      return;
    }
  }
  this._loading = true;
  this._error = null;
  try {
    const response = await this.data({
      page: this._view.page,
      rows: this._view.rows,
      sortColumn: this._view.sortColumn,
      sortDirection: this._view.sortDirection,
      searchQuery: this._view.searchQuery
    });
    if (!this.nocache) {
      const cacheKey = __privateMethod(this, _GdsTable_instances, getCacheKey_fn).call(this);
      __privateGet(this, _cache)[cacheKey] = {
        rows: response.rows,
        total: response.total,
        timestamp: Date.now()
      };
    }
    this._rowsState = response.rows;
    this._total = response.total;
    this._selected.clear();
    this._loaded = false;
    this.dispatchCustomEvent("gds-table-data-loaded", {
      detail: response,
      bubbles: true
    });
  } catch (error) {
    this._error = error;
    this.dispatchCustomEvent("gds-table-data-error", {
      detail: error,
      bubbles: true
    });
  } finally {
    this._loading = false;
  }
};
/**
 * Retrieves template content for the given slot name.
 * Uses caching to prevent repeated DOM queries for better performance in large tables.
 */
getSlotContent_fn = function(slot) {
  if (!slot) return null;
  if (!__privateGet(this, _templateCache).has(slot)) {
    const template = this.querySelector(
      `template[name="${slot}"]`
    );
    __privateGet(this, _templateCache).set(slot, template);
  }
  return __privateGet(this, _templateCache).get(slot)?.content.cloneNode(true);
};
renderCell_fn = function(config, row) {
  if (!config) return null;
  if (Array.isArray(config)) {
    return config.map((c) => __privateMethod(this, _GdsTable_instances, renderCell_fn).call(this, c, row));
  }
  const resolve = (value) => typeof value === "function" ? value(row) : value;
  switch (config.type) {
    case "badge": {
      const variant = resolve(config.variant) || "information";
      const size = resolve(config.size) || __privateGet(this, _GdsTable_instances, Density_get).badge;
      return html`
          <gds-badge size="${size}" variant="${variant}">
            ${resolve(config.value)}
          </gds-badge>
        `;
    }
    case "image": {
      const src = resolve(config.src);
      if (!src) return null;
      const width = resolve(config.width) || "24px";
      const height = resolve(config.height) || "24px";
      const borderRadius = resolve(config["border-radius"]) || "max";
      const objectFit = resolve(config["object-fit"]) || "cover";
      const alt = resolve(config.alt) || "";
      return html`
          <gds-img
            src="${src}"
            alt="${alt}"
            width="${width}"
            height="${height}"
            border-radius="${borderRadius}"
            object-fit="${objectFit}"
            object-position="center"
          ></gds-img>
        `;
    }
    case "icon": {
      const template = resolve(config.template);
      const size = resolve(config.size);
      const color = resolve(config.color);
      const clonedSlot = __privateMethod(this, _GdsTable_instances, getSlotContent_fn).call(this, template);
      if (!clonedSlot) return null;
      if (clonedSlot instanceof DocumentFragment) {
        const iconElement = clonedSlot.firstElementChild;
        if (iconElement) {
          if (size) iconElement.setAttribute("size", size);
          if (color) iconElement.setAttribute("color", color);
        }
      }
      return clonedSlot;
    }
    case "button": {
      const size = resolve(config.size) || __privateGet(this, _GdsTable_instances, Density_get).button;
      const variant = resolve(config.variant);
      const rank = resolve(config.rank);
      const label = resolve(config.label);
      const template = resolve(config.template);
      const clonedSlot = __privateMethod(this, _GdsTable_instances, getSlotContent_fn).call(this, template);
      const content = [label, clonedSlot];
      return html`
          <gds-button
            size="${size}"
            variant="${variant || "neutral"}"
            rank="${rank || "secondary"}"
            @click="${(e) => {
        e.stopPropagation();
        config.onClick(row);
      }}"
          >
            ${content}
          </gds-button>
        `;
    }
    case "link": {
      const href = resolve(config.href);
      if (!href) return null;
      const label = resolve(config.label);
      const target = resolve(config.target);
      const download = resolve(config.download);
      const template = resolve(config.template);
      const clonedSlot = __privateMethod(this, _GdsTable_instances, getSlotContent_fn).call(this, template);
      const content = [label, clonedSlot];
      return html`
          <gds-link
            href=${ifDefined(href)}
            target=${ifDefined(target)}
            .download=${download}
            text-decoration="underline"
          >
            ${content}
          </gds-link>
        `;
    }
    case "context-menu": {
      const items = config.items;
      const size = __privateGet(this, _GdsTable_instances, Density_get).button;
      return html`
          <gds-context-menu>
            <gds-button
              slot="trigger"
              size="${size}"
              rank="tertiary"
              label="${msg("Actions")}"
            >
              <gds-icon-dot-grid-one-horizontal></gds-icon-dot-grid-one-horizontal>
            </gds-button>
            ${items.map((item) => {
        const label = resolve(item.label);
        return html`
                <gds-menu-item @click="${() => item.onClick(row)}">
                  ${label}
                </gds-menu-item>
              `;
      })}
          </gds-context-menu>
        `;
    }
    case "formatted-number": {
      const value = resolve(config.value);
      const formatter = Table.FormatNumber[config.format || "decimalsAndThousands"];
      return formatter(value, config.locale, config.currency, config.decimals);
    }
    case "formatted-account": {
      const value = resolve(config.value);
      const formatter = Table.FormatAccount[config.format || "seb-account"];
      return formatter(value);
    }
    case "formatted-date": {
      const value = resolve(config.value);
      const formatter = Table.FormatDate[config.format || "dateLong"];
      return formatter(value, config.locale);
    }
    default:
      return null;
  }
};
/**
 * Renders the content of a table cell with support for custom transformations,
 * cell types, and responsive mobile labels.
 *
 * Value resolution priority:
 * 1. column.value - Direct transform function
 * 2. cell.value - Cell type configuration (badge, button, etc.)
 * 3. row[column.key] - Raw data value
 */
renderCellContent_fn = function(row, column) {
  const { cell } = column;
  let value;
  if (column.value) {
    value = column.value(row);
  } else if (cell?.value) {
    value = __privateMethod(this, _GdsTable_instances, renderCell_fn).call(this, cell.value, row);
  } else {
    value = row[column.key];
  }
  const processedValue = column.justify ? html`<span>${value}</span>` : value;
  const isResponsive = this._isMobile && this.responsive;
  const mobileLabel = isResponsive ? html`
          <span class="column-label" aria-hidden="true">
            ${column.label}:
          </span>
        ` : null;
  const ariaLabel = isResponsive ? `${column.label}: ` : "";
  return html`
      <div class="cell-content" aria-label="${ariaLabel}">
        ${[
    mobileLabel,
    __privateMethod(this, _GdsTable_instances, renderCell_fn).call(this, cell?.lead, row),
    processedValue,
    __privateMethod(this, _GdsTable_instances, renderCell_fn).call(this, cell?.trail, row)
  ]}
      </div>
    `;
};
renderSortIcon_fn = function(column) {
  const isSorted = this._view.sortColumn === column.key;
  const sortDirection = this._view.sortDirection;
  if (isSorted) {
    return sortDirection === "asc" ? html`<gds-icon-sort-up size="m"></gds-icon-sort-up>` : html`<gds-icon-sort-down size="m"></gds-icon-sort-down>`;
  }
  return html`<gds-icon-sort-up size="m"></gds-icon-sort-up>`;
};
hasHeaderContent_fn = function() {
  return this.searchable || this.settings || this.querySelector('[slot="header-lead"]') || this.querySelector('[slot="header-trail"]');
};
renderHeaderControls_fn = function() {
  if (this.plain || !__privateMethod(this, _GdsTable_instances, hasHeaderContent_fn).call(this)) return null;
  return html`
      <div class="header">
        <div class="lead">
          ${when(
    this.searchable,
    () => html`
              <gds-input
                type="text"
                size="${__privateGet(this, _GdsTable_instances, Density_get).input}"
                plain
                clearable
                label="${this.searchLabel || msg("Search table")}"
                .value=${this._view.searchQuery}
                @input=${__privateMethod(this, _GdsTable_instances, handleSearch_fn)}
                @gds-input-cleared=${__privateMethod(this, _GdsTable_instances, handleSearchClear_fn)}
                width="100%; l{240px}"
                min-width="240px"
              >
                <gds-icon-magnifying-glass
                  slot="lead"
                ></gds-icon-magnifying-glass>
              </gds-input>
            `
  )}
          <slot name="header-lead"></slot>
        </div>
        <div class="trail">
          <slot name="header-trail"></slot>
          ${when(
    this.settings,
    () => html`
              <gds-dropdown
                multiple
                plain
                size="${__privateGet(this, _GdsTable_instances, Density_get).dropdown}"
                label="${msg("Select visible columns")}"
                searchable
                .value=${Array.from(this._view.visibleColumns)}
                @change=${__privateMethod(this, _GdsTable_instances, handleColumnVisibility_fn)}
              >
                <span slot="trigger">${msg("Columns")}</span>
                ${this.columns.map(
      (column) => html`
                    <gds-option
                      value=${column.key}
                      ?selected=${this._view.visibleColumns.has(column.key)}
                    >
                      ${column.label}
                    </gds-option>
                  `
    )}
              </gds-dropdown>
            `
  )}
        </div>
      </div>
    `;
};
renderColumnHeader_fn = function(column) {
  const isSorted = this._view.sortColumn === column.key;
  const sortDirection = this._view.sortDirection;
  let ariaLabel = column.label;
  if (column.sortable) {
    if (isSorted) {
      const direction = sortDirection === "asc" ? msg("ascending") : msg("descending");
      ariaLabel = `${column.label}, ${msg("sorted")} ${direction}`;
    } else {
      ariaLabel = `${column.label}, ${msg("sortable")}`;
    }
  }
  const classes = classMap({
    sortable: !!column.sortable,
    sorted: isSorted,
    "sort-asc": isSorted && sortDirection === "asc",
    "sort-desc": isSorted && sortDirection === "desc",
    [`align-${column.align}`]: !!column.align,
    [`justify-${column.justify}`]: !!column.justify,
    wrap: Boolean(column.width)
  });
  const style = styleMap({
    "--cell-width": column.width
  });
  return html`
      <th
        class=${classes}
        style=${style}
        aria-sort="${isSorted ? sortDirection === "asc" ? "ascending" : "descending" : "none"}"
        @click=${column.sortable ? () => __privateMethod(this, _GdsTable_instances, handleSort_fn).call(this, column.key) : null}
      >
        <div class="column-header">
          <span class="column-label" aria-label="${ariaLabel}">
            ${column.label}
          </span>
          ${when(
    column.sortable,
    () => html`
              <span class="sort-icon">${__privateMethod(this, _GdsTable_instances, renderSortIcon_fn).call(this, column)}</span>
            `
  )}
        </div>
      </th>
    `;
};
renderActionsHeader_fn = function() {
  if (!this.actions || typeof this.actions === "function") return null;
  const label = this.actions.label || msg("Actions");
  const classes = classMap({
    actions: true,
    [`align-${this.actions.align}`]: !!this.actions.align,
    [`justify-${this.actions.justify}`]: !!this.actions.justify
  });
  return html`
      <th class="${classes}">
        <div class="column-header">
          <div class="column-label">${label}</div>
        </div>
      </th>
    `;
};
renderSelectableHeader_fn = function() {
  if (!this.selectable) return null;
  return html`
      <th class="checkbox-cell">
        ${__privateMethod(this, _GdsTable_instances, renderCheckbox_fn).call(this, {
    checked: __privateGet(this, _GdsTable_instances, isAllSelected_get),
    indeterminate: __privateGet(this, _GdsTable_instances, isPartialSelection_get),
    ariaLabel: msg("Select all rows"),
    onToggle: () => __privateMethod(this, _GdsTable_instances, handleSelectAll_fn).call(this, {})
  })}
      </th>
    `;
};
renderColumnHeaders_fn = function() {
  return this.columns.filter((column) => this._view.visibleColumns.has(column.key)).map((column) => __privateMethod(this, _GdsTable_instances, renderColumnHeader_fn).call(this, column));
};
renderTableHeader_fn = function() {
  return html`
      <thead>
        <tr>
          ${[
    __privateMethod(this, _GdsTable_instances, renderSelectableHeader_fn).call(this),
    __privateMethod(this, _GdsTable_instances, renderColumnHeaders_fn).call(this),
    __privateMethod(this, _GdsTable_instances, renderActionsHeader_fn).call(this)
  ]}
        </tr>
      </thead>
    `;
};
renderTableCell_fn = function(row, column) {
  const classes = classMap({
    [`align-${column.align}`]: !!column.align,
    [`justify-${column.justify}`]: !!column.justify,
    wrap: Boolean(column.width)
  });
  const style = styleMap({
    "--cell-width": column.width
  });
  return html`
      <td style=${style} class=${classes}>
        ${__privateMethod(this, _GdsTable_instances, renderCellContent_fn).call(this, row, column)}
      </td>
    `;
};
renderSelectableCell_fn = function(index) {
  if (!this.selectable) return null;
  const selectRowLabel = `${msg("Select row")} ${index + 1}`;
  return html`
      <td class="checkbox-cell">
        ${__privateMethod(this, _GdsTable_instances, renderCheckbox_fn).call(this, {
    checked: this._selected.has(index),
    indeterminate: false,
    ariaLabel: selectRowLabel,
    onToggle: () => __privateMethod(this, _GdsTable_instances, handleRowSelect_fn).call(this, index, {
      detail: { checked: !this._selected.has(index) }
    })
  })}
      </td>
    `;
};
renderRowCells_fn = function(row) {
  return this.columns.filter((column) => this._view.visibleColumns.has(column.key)).map((column) => __privateMethod(this, _GdsTable_instances, renderTableCell_fn).call(this, row, column));
};
renderActionsCell_fn = function(row, index) {
  if (!this.actions) return null;
  if (typeof this.actions === "function") {
    return html`
        <td class="actions-cell">
          <div class="cell-content">${this.actions(row, index)}</div>
        </td>
      `;
  }
  const content = __privateMethod(this, _GdsTable_instances, renderCell_fn).call(this, this.actions.cell, row);
  const classes = classMap({
    "actions-cell": true,
    [`align-${this.actions.align}`]: !!this.actions.align,
    [`justify-${this.actions.justify}`]: !!this.actions.justify
  });
  return html`
      <td class="${classes}">
        <div class="cell-content">${content}</div>
      </td>
    `;
};
renderTableRow_fn = function(row, index) {
  return html`
      <tr
        class=${classMap({
    selected: this._selected.has(index),
    loading: this._loading
  })}
      >
        ${[
    __privateMethod(this, _GdsTable_instances, renderSelectableCell_fn).call(this, index),
    __privateMethod(this, _GdsTable_instances, renderRowCells_fn).call(this, row),
    __privateMethod(this, _GdsTable_instances, renderActionsCell_fn).call(this, row, index)
  ]}
      </tr>
    `;
};
renderCheckbox_fn = function({
  checked,
  indeterminate = false,
  disabled = false,
  ariaLabel,
  onToggle
}) {
  const toggle = (e) => {
    e.stopPropagation();
    if (disabled) return;
    onToggle();
  };
  const onKey = (e) => {
    if (e.key === " " || e.key === "Enter") {
      e.preventDefault();
      toggle(e);
    }
  };
  return html`
      <div
        class="rbcb-wrapper"
        role="checkbox"
        aria-checked=${indeterminate ? "mixed" : checked ? "true" : "false"}
        aria-label=${ariaLabel}
        @click=${toggle}
        @keydown=${onKey}
      >
        <input
          type="checkbox"
          class="visually-hidden-checkbox"
          .checked=${checked}
          .indeterminate=${indeterminate}
          ?disabled=${disabled}
          aria-hidden="true"
          @change=${toggle}
        />
        ${Table.Checkbox({
    checked,
    indeterminate,
    disabled,
    invalid: false
  })}
      </div>
    `;
};
renderSkeletonCell_fn = function(column) {
  const isResponsive = this._isMobile && this.responsive;
  const mobileLabel = isResponsive ? html`<span class="skeleton skeleton-text"></span>` : null;
  return html`
      <div class="cell-content">
        ${mobileLabel}
        <span class="skeleton skeleton-text"></span>
      </div>
    `;
};
renderSkeletonRow_fn = function(index) {
  return html`
      <tr class="skeleton-row">
        ${when(
    this.selectable,
    () => html`
            <td class="checkbox-cell">
              <span class="skeleton skeleton-checkbox"></span>
            </td>
          `
  )}
        ${this.columns.filter((column) => this._view.visibleColumns.has(column.key)).map((column) => html`<td>${__privateMethod(this, _GdsTable_instances, renderSkeletonCell_fn).call(this, column)}</td>`)}
        ${when(
    this.actions,
    () => html`
            <td class="actions-cell">
              <div class="cell-content">
                <span class="skeleton skeleton-action"></span>
              </div>
            </td>
          `
  )}
      </tr>
    `;
};
renderTableBody_fn = function() {
  if (this._loading && this._loaded) {
    const skeletonRows = Array.from(
      { length: this._view.rows },
      (_, i) => __privateMethod(this, _GdsTable_instances, renderSkeletonRow_fn).call(this, i)
    );
    return html`<tbody aria-busy="true" aria-live="polite">
        ${skeletonRows}
      </tbody>`;
  }
  return html`
      <tbody aria-live="polite">
        ${this._rowsState.map((row, index) => __privateMethod(this, _GdsTable_instances, renderTableRow_fn).call(this, row, index))}
      </tbody>
    `;
};
renderTable_fn = function() {
  const CLASSES = classMap({
    responsive: this.responsive,
    data: true,
    [`variant-${this.variant}`]: true,
    loading: this._loading,
    loaded: !this._loading && !this._loaded
  });
  const caption = `${this.summary ? this.summary + ", " : ""}${msg("Data table with")} ${this._total} ${msg("rows")}`;
  return html`
      <gds-card
        variant="${this.variant}"
        padding="0"
        border-radius="m"
        border-width="0; s{5xs}"
        class="table-card"
      >
        <div class=${CLASSES} tabindex="0">
          <table aria-label="${caption}">
            <caption class="visually-hidden">
              ${caption}
            </caption>
            ${__privateMethod(this, _GdsTable_instances, renderTableHeader_fn).call(this)} ${__privateMethod(this, _GdsTable_instances, renderTableBody_fn).call(this)}
          </table>
        </div>
      </gds-card>
    `;
};
renderErrorState_fn = function() {
  return html`
      <gds-card variant="secondary" border-radius="m">
        <slot name="error">
          <gds-text tag="p">${msg("Error loading data")}</gds-text>
          <gds-button
            size="small"
            label="${msg("Retry loading data")}"
            @click=${() => __privateMethod(this, _GdsTable_instances, loadData_fn).call(this)}
          >
            ${msg("Retry")}
          </gds-button>
        </slot>
      </gds-card>
    `;
};
renderEmptyState_fn = function() {
  const hasSearch = this._view.searchQuery.length > 0;
  if (hasSearch) {
    return html`
        <gds-card variant="secondary" border-radius="m">
          <slot name="no-results">
            <gds-flex flex-direction="column" align-items="flex-start" gap="s">
              <gds-text tag="p" font="heading-s">
                ${msg("No results found")}
              </gds-text>
              <gds-text tag="p" font="detail-book-s">
                ${msg("No results for")} "${this._view.searchQuery}"
              </gds-text>
              <gds-button
                size="small"
                label="${msg("Clear search for")} ${this._view.searchQuery}"
                @click=${__privateMethod(this, _GdsTable_instances, handleSearchClear_fn)}
              >
                ${msg("Clear search")}
              </gds-button>
            </gds-flex>
          </slot>
        </gds-card>
      `;
  }
  return html`
      <gds-card variant="secondary" border-radius="m">
        <slot name="empty">
          <gds-text tag="p" font="heading-s">
            ${msg("No data available")}
          </gds-text>
        </slot>
      </gds-card>
    `;
};
renderFooter_fn = function() {
  if (this.plain || this._total < 1) return null;
  const start = (this._view.page - 1) * this._view.rows + 1;
  const end = Math.min(this._view.page * this._view.rows, this._total);
  const summaryString = `${start}\u2013${end} ${msg("of")} ${this._total}`;
  return html`
      <gds-pagination
        .page=${this._view.page}
        .rows=${this._view.rows}
        .options=${this.options}
        .total=${this._total}
        .density=${this.density}
        .label=${summaryString}
        @gds-page-change=${__privateMethod(this, _GdsTable_instances, handlePageChange_fn)}
        @gds-rows-change=${__privateMethod(this, _GdsTable_instances, handlePageSizeChange_fn)}
        width="100%"
      >
      </gds-pagination>
    `;
};
renderHeadline_fn = function() {
  if (this.plain) return null;
  if (this.headline || this.summary) {
    return html`
        <gds-flex flex-direction="column" gap="4xs">
          <gds-text
            tag="${this.headlineTag}"
            font="heading-s"
            text-wrap="balance"
            max-width="80ch"
          >
            ${this.headline}
          </gds-text>
          <gds-text
            tag="p"
            font=${this.density === "compact" ? "body-regular-s" : "body-regular-m"}
            text-wrap="balance"
            max-width="80ch"
          >
            ${this.summary}
          </gds-text>
        </gds-flex>
        ${when(
      this.searchable || this.settings,
      () => html`<gds-divider color="subtle-01"></gds-divider>`,
      () => html``
    )}
      `;
  }
};
handleSearch_fn = async function(e) {
  const input = e.target;
  this._view = {
    ...this._view,
    searchQuery: input.value,
    page: 1
  };
  await __privateMethod(this, _GdsTable_instances, loadData_fn).call(this);
};
handleSearchClear_fn = async function() {
  this._view = {
    ...this._view,
    searchQuery: "",
    page: 1
  };
  await __privateMethod(this, _GdsTable_instances, loadData_fn).call(this);
};
handleSort_fn = async function(columnKey) {
  const newDirection = this._view.sortColumn === columnKey && this._view.sortDirection === "asc" ? "desc" : "asc";
  this._view = {
    ...this._view,
    sortColumn: columnKey,
    sortDirection: newDirection,
    page: 1
  };
  this.dispatchCustomEvent("gds-sort-change", {
    detail: {
      sortColumn: columnKey,
      sortDirection: newDirection
    },
    bubbles: true
  });
  await __privateMethod(this, _GdsTable_instances, loadData_fn).call(this);
};
handlePageChange_fn = async function(e) {
  this._view = {
    ...this._view,
    page: e.detail.page
  };
  this.dispatchCustomEvent("gds-page-change", {
    detail: e.detail,
    bubbles: true
  });
  await __privateMethod(this, _GdsTable_instances, loadData_fn).call(this);
};
handlePageSizeChange_fn = async function(e) {
  this._view = {
    ...this._view,
    rows: e.detail.rows,
    page: 1
  };
  this.dispatchCustomEvent("gds-rows-change", {
    detail: e.detail,
    bubbles: true
  });
  await __privateMethod(this, _GdsTable_instances, loadData_fn).call(this);
};
/**
 * Handles column visibility dropdown changes
 * Updates visible columns set and triggers re-render
 */
handleColumnVisibility_fn = function(e) {
  const selectedColumns = e.detail.value;
  this._view = {
    ...this._view,
    visibleColumns: new Set(selectedColumns)
  };
  this.requestUpdate();
};
/**
 * Handles select all checkbox change
 * Toggles between all selected and none selected
 */
handleSelectAll_fn = function(e) {
  if (__privateGet(this, _GdsTable_instances, isAllSelected_get)) {
    __privateMethod(this, _GdsTable_instances, clearSelectionInternal_fn).call(this);
  } else {
    __privateMethod(this, _GdsTable_instances, selectAllInternal_fn).call(this);
  }
  __privateMethod(this, _GdsTable_instances, emitSelectionChange_fn).call(this);
};
/**
 * Handles individual row selection change
 */
handleRowSelect_fn = function(index, e) {
  const isChecked = e.detail.checked;
  if (isChecked) {
    this._selected.add(index);
  } else {
    this._selected.delete(index);
  }
  __privateMethod(this, _GdsTable_instances, emitSelectionChange_fn).call(this);
  this.requestUpdate();
};
/**
 * Internal method to select all rows
 */
selectAllInternal_fn = function() {
  this._selected = new Set(this._rowsState.map((_, i) => i));
  this.requestUpdate();
};
/**
 * Internal method to clear all selections
 */
clearSelectionInternal_fn = function() {
  this._selected.clear();
  this.requestUpdate();
};
/**
 * Emits selection change event with current selection details
 */
emitSelectionChange_fn = function() {
  this.dispatchCustomEvent("gds-table-selection", {
    detail: {
      selectedIndices: Array.from(this._selected),
      selectedData: Array.from(this._selected).map((i) => this._rowsState[i]),
      count: this._selected.size
    },
    bubbles: true
  });
};
/**
 * Initializes scroll tracking for the table data container.
 * Sets up event listeners and performs initial scroll state check.
 */
initializeScrollTracking_fn = function() {
  const dataContainer = this.shadowRoot?.querySelector(".data");
  if (!dataContainer) return;
  const updateScrollState = () => {
    __privateMethod(this, _GdsTable_instances, updateVerticalScrollState_fn).call(this, dataContainer);
    __privateMethod(this, _GdsTable_instances, updateHorizontalScrollState_fn).call(this, dataContainer);
  };
  dataContainer.addEventListener("scroll", updateScrollState);
  updateScrollState();
};
/**
 * Updates CSS classes based on vertical scroll position.
 * Adds 'scrolled' class when scrolled down from top.
 */
updateVerticalScrollState_fn = function(container) {
  const { scrollTop } = container;
  if (scrollTop > 0) {
    container.classList.add("scrolled");
  } else {
    container.classList.remove("scrolled");
  }
};
/**
 * Updates CSS classes based on horizontal scroll position.
 * Manages 'scrolled-x-start', 'scrolled-x-middle', and 'scrolled-x-end' classes
 * to indicate scroll position for styling purposes (e.g., shadows, sticky columns).
 */
updateHorizontalScrollState_fn = function(container) {
  const { scrollLeft, scrollWidth, clientWidth } = container;
  const maxScrollLeft = scrollWidth - clientWidth;
  if (scrollLeft <= 0) {
    container.classList.add("scrolled-x-start");
    container.classList.remove("scrolled-x-middle", "scrolled-x-end");
  } else if (scrollLeft >= maxScrollLeft - 1) {
    container.classList.add("scrolled-x-end");
    container.classList.remove("scrolled-x-start", "scrolled-x-middle");
  } else {
    container.classList.add("scrolled-x-middle");
    container.classList.remove("scrolled-x-start", "scrolled-x-end");
  }
};
GdsTable.styles = Table.Styles;
__decorateClass([
  property()
], GdsTable.prototype, "headline", 2);
__decorateClass([
  property({
    attribute: "headline-tag",
    type: String,
    reflect: true
  })
], GdsTable.prototype, "headlineTag", 2);
__decorateClass([
  property()
], GdsTable.prototype, "summary", 2);
__decorateClass([
  property({
    attribute: "search-label",
    type: String
  })
], GdsTable.prototype, "searchLabel", 2);
__decorateClass([
  property({ type: Array })
], GdsTable.prototype, "options", 2);
__decorateClass([
  property({ type: Number })
], GdsTable.prototype, "page", 2);
__decorateClass([
  property({ type: Number })
], GdsTable.prototype, "rows", 2);
__decorateClass([
  property({ type: Array })
], GdsTable.prototype, "columns", 2);
__decorateClass([
  property()
], GdsTable.prototype, "data", 2);
__decorateClass([
  property({ reflect: false })
], GdsTable.prototype, "density", 2);
__decorateClass([
  property({ type: Boolean, reflect: false })
], GdsTable.prototype, "selectable", 2);
__decorateClass([
  property({ type: Boolean, reflect: false })
], GdsTable.prototype, "responsive", 2);
__decorateClass([
  property({ type: Boolean, reflect: false })
], GdsTable.prototype, "plain", 2);
__decorateClass([
  property({ type: Boolean, reflect: false })
], GdsTable.prototype, "searchable", 2);
__decorateClass([
  property({ type: Boolean, reflect: false })
], GdsTable.prototype, "settings", 2);
__decorateClass([
  property({ type: Boolean, reflect: false })
], GdsTable.prototype, "striped", 2);
__decorateClass([
  property()
], GdsTable.prototype, "actions", 2);
__decorateClass([
  property({ type: Boolean, reflect: false })
], GdsTable.prototype, "nocache", 2);
__decorateClass([
  property()
], GdsTable.prototype, "dataLoadKey", 2);
__decorateClass([
  styleExpressionProperty({
    ...forSpaceTokensAndCustomValues,
    property: "--_table-height",
    selector: ".data"
  })
], GdsTable.prototype, "height", 2);
__decorateClass([
  property()
], GdsTable.prototype, "variant", 2);
__decorateClass([
  state()
], GdsTable.prototype, "_isMobile", 2);
__decorateClass([
  watchMediaQuery("(max-width: 768px)")
], GdsTable.prototype, "_handleMobile", 1);
__decorateClass([
  state()
], GdsTable.prototype, "_view", 2);
__decorateClass([
  state()
], GdsTable.prototype, "_loaded", 2);
__decorateClass([
  state()
], GdsTable.prototype, "_loading", 2);
__decorateClass([
  state()
], GdsTable.prototype, "_rowsState", 2);
__decorateClass([
  state()
], GdsTable.prototype, "_total", 2);
__decorateClass([
  state()
], GdsTable.prototype, "_selected", 2);
__decorateClass([
  state()
], GdsTable.prototype, "_error", 2);
__decorateClass([
  watch("dataLoadKey"),
  watch("data")
], GdsTable.prototype, "_onDataChange", 1);
__decorateClass([
  watch("columns")
], GdsTable.prototype, "_onColumnsChange", 1);
GdsTable = __decorateClass([
  localized(),
  gdsCustomElement("gds-table", {
    dependsOn: Table.Dependencies
  })
], GdsTable);
export {
  GdsTable
};
