import { t as e } from "./sanitize-CDxuPfMB.js";
import { n as t } from "./utils-C_mWfcFX.js";
import { n, r } from "./sorting-CclEKVQk.js";
import { r as i, t as a } from "./a11y-CuHKgVSx.js";
import { i as o, t as s } from "./keyboard-wOEoCCWj.js";
//#region src/components/data-table/renderers.ts
function c(e) {
	if (e === 0) return "0 B";
	let t = [
		"B",
		"KB",
		"MB",
		"GB",
		"TB"
	], n = 1024, r = Math.floor(Math.log(e) / Math.log(n)), i = Math.min(r, t.length - 1), a = t[i];
	return a === void 0 ? `${String(e)} B` : `${(e / n ** +i).toFixed(2)} ${a}`;
}
function l(e) {
	let t = Date.now() - e.getTime(), n = Math.floor(t / 1e3), r = Math.floor(n / 60), i = Math.floor(r / 60), a = Math.floor(i / 24);
	return n < 60 ? `${String(n)}s ago` : r < 60 ? `${String(r)}m ago` : i < 24 ? `${String(i)}h ago` : `${String(a)}d ago`;
}
function u(e) {
	return e == null ? "" : typeof e == "string" ? e : typeof e == "number" || typeof e == "boolean" ? String(e) : JSON.stringify(e);
}
function d(t, n, r) {
	let i = u(t);
	switch (n) {
		case "text": return e(i);
		case "badge": {
			let t = e(i), n = r?.badgeMap, a = "default";
			if (typeof n == "object" && n) {
				let e = n[i];
				e !== void 0 && (a = e);
			}
			return `<span class="cmm-badge cmm-badge--${e(a)}">${t}</span>`;
		}
		case "link": {
			let t = e(i);
			return /^https?:\/\//.test(i) ? `<a href="${t}" class="cmm-link" target="_blank" rel="noopener noreferrer">${t}</a>` : t;
		}
		case "code": return `<code class="cmm-code">${e(i)}</code>`;
		case "bytes": {
			let n = typeof t == "number" ? t : parseFloat(i);
			return e(Number.isNaN(n) ? i : c(n));
		}
		case "datetime": {
			let n = t instanceof Date ? t : new Date(i);
			if (Number.isNaN(n.getTime())) return e(i);
			let a = r?.format;
			return e(a === "iso" ? n.toISOString() : a === "locale" ? n.toLocaleString() : l(n));
		}
		case "number": {
			let n = typeof t == "number" ? t : parseFloat(i);
			return e(Number.isNaN(n) ? i : n.toLocaleString());
		}
		default: return e(i);
	}
}
//#endregion
//#region src/components/data-table/export.ts
function f(e) {
	let t = e == null ? "" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? String(e) : JSON.stringify(e);
	return t.includes(",") || t.includes("\"") || t.includes("\n") || t.includes("\r") ? `"${t.replace(/"/g, "\"\"")}"` : t;
}
function p(e, t) {
	let n = [e.map((e) => f(e.label)).join(",")];
	for (let r of t) {
		let t = [];
		for (let n = 0; n < e.length; n++) {
			let e = r[n];
			t.push(f(e));
		}
		n.push(t.join(","));
	}
	return n.join("\n");
}
function m(e, t) {
	let n = [];
	for (let r of t) {
		let t = {};
		for (let n = 0; n < e.length; n++) {
			let i = e[n];
			i !== void 0 && (t[i.key] = r[n] ?? null);
		}
		n.push(t);
	}
	return JSON.stringify(n, null, 2);
}
async function h(e) {
	await navigator.clipboard.writeText(e);
}
//#endregion
//#region src/components/data-table/index.ts
function g(e) {
	if (typeof e == "string") {
		let t = document.querySelector(e);
		if (!t) throw Error(`DataTable container not found: ${e}`);
		return t;
	}
	return e;
}
var _ = class {
	container;
	columns;
	config;
	rows = [];
	sortState = null;
	currentPage = 0;
	wrapperEl = null;
	tableEl = null;
	liveRegion = null;
	tableId;
	captionId;
	focusedRow = 0;
	focusedCol = 0;
	constructor(e) {
		this.container = g(e.container), this.columns = e.columns, this.config = e, this.tableId = t("cmm-data-table"), this.captionId = t("cmm-data-table-caption"), e.data !== void 0 && (this.rows = e.data), this.liveRegion = i("polite"), this.render();
	}
	setData(e) {
		this.rows = e, this.currentPage = 0, this.focusedRow = 0, this.focusedCol = 0, this.render(), this.announceUpdate(`Table updated with ${String(e.length)} rows`);
	}
	appendRows(e) {
		this.rows = [...this.rows, ...e], this.render(), this.announceUpdate(`Added ${String(e.length)} rows, total ${String(this.rows.length)} rows`);
	}
	setLoading(e) {
		if (!this.wrapperEl) return;
		let t = this.wrapperEl.querySelector(".cmm-data-table__loading");
		if (e) {
			if (!t) {
				let e = document.createElement("div");
				e.className = "cmm-data-table__loading", e.setAttribute("role", "status"), e.setAttribute("aria-live", "polite");
				let t = document.createElement("span");
				t.textContent = "Loading...", e.appendChild(t), this.wrapperEl.appendChild(e), this.announceUpdate("Loading data");
			}
		} else t && (t.remove(), this.announceUpdate("Data loaded"));
	}
	clear() {
		this.rows = [], this.currentPage = 0, this.focusedRow = 0, this.focusedCol = 0, this.render(), this.announceUpdate("Table cleared");
	}
	getRowCount() {
		return this.rows.length;
	}
	destroy() {
		this.container.innerHTML = "", this.wrapperEl = null, this.tableEl = null, this.liveRegion?.destroy(), this.liveRegion = null;
	}
	announceUpdate(e) {
		this.liveRegion?.announce(e);
	}
	getPageRows() {
		let e = this.config.pagination;
		if (e === void 0) return this.rows;
		let t = this.currentPage * e.pageSize, n = t + e.pageSize;
		return this.rows.slice(t, n);
	}
	getTotalPages() {
		let e = this.config.pagination;
		return e === void 0 ? 1 : Math.max(1, Math.ceil(this.rows.length / e.pageSize));
	}
	handleSort(e) {
		let t = this.columns.find((t) => t.key === e);
		if (t?.sortable !== !0) return;
		let r = n(this.sortState?.key ?? null, this.sortState?.direction ?? null, e);
		this.sortState = r;
		let i = r?.direction ?? null;
		if (i === null) this.announceUpdate(`${t.label} sort cleared`);
		else {
			let e = i === "asc" ? "ascending" : "descending";
			this.announceUpdate(`Sorted by ${t.label} ${e}`);
		}
		this.config.onSort !== void 0 && this.config.onSort(e, i), this.currentPage = 0, this.render();
	}
	getSortedRows() {
		if (this.sortState === null) return [...this.rows];
		let { key: e, direction: t } = this.sortState, n = this.columns.findIndex((t) => t.key === e);
		return n < 0 || t === null ? [...this.rows] : r(this.rows, t, (e) => e[n]);
	}
	buildSortIcon(e) {
		let t = this.sortState?.key === e ? "cmm-data-table__sort-icon--active" : "";
		return this.sortState?.key === e ? this.sortState.direction === "asc" ? `<span class="cmm-data-table__sort-icon ${t}" aria-hidden="true">&#8593;</span>` : `<span class="cmm-data-table__sort-icon ${t}" aria-hidden="true">&#8595;</span>` : `<span class="cmm-data-table__sort-icon ${t}" aria-hidden="true">&#8597;</span>`;
	}
	getSortLabel(e) {
		return this.sortState?.key === e ? this.sortState.direction === "asc" ? "ascending" : "descending" : "none";
	}
	handleKeyDown(e) {
		let t = e.target;
		if (this.tableEl?.contains(t) !== !0) return;
		let n = this.tableEl.querySelector("tbody");
		if (!n) return;
		let r = Array.from(n.querySelectorAll("tr")), i = this.getPageRows();
		if (i.length === 0) return;
		let a = o(e, {
			columns: this.columns.length,
			rows: i.length,
			currentCol: this.focusedCol,
			currentRow: this.focusedRow,
			wrap: !1
		});
		if (a.handled && (e.preventDefault(), this.focusedRow = a.row, this.focusedCol = a.col, this.focusCell(r)), e.key === s.ENTER || e.key === s.SPACE) {
			let t = this.config.pagination, n = (t === void 0 ? 0 : this.currentPage * t.pageSize) + this.focusedRow, r = this.rows[n];
			r !== void 0 && this.config.onRowClick !== void 0 && (e.preventDefault(), this.config.onRowClick(r, n));
		}
	}
	focusCell(e) {
		let t = e[this.focusedRow];
		if (t === void 0) return;
		let n = Array.from(t.querySelectorAll("td"))[this.focusedCol];
		if (n !== void 0) {
			n.focus();
			let e = n.textContent;
			a(`${this.columns[this.focusedCol]?.label ?? ""}: ${e}`, "polite");
		}
	}
	render() {
		this.container.innerHTML = "";
		let t = document.createElement("div");
		t.className = "cmm-data-table", this.wrapperEl = t;
		let n = this.config.pagination;
		n !== void 0 && (n.position === "top" || n.position === "both") && t.appendChild(this.buildPagination("top")), this.config.exportFormats !== void 0 && this.config.exportFormats.length > 0 && t.appendChild(this.buildExportBar());
		let r = this.getSortedRows(), i = this.rows;
		this.rows = r;
		let a = this.getPageRows();
		this.rows = i;
		let o = document.createElement("table");
		o.className = "cmm-data-table__table", o.id = this.tableId, o.setAttribute("role", "grid"), o.setAttribute("aria-labelledby", this.captionId), o.setAttribute("aria-rowcount", String(this.rows.length)), o.setAttribute("aria-colcount", String(this.columns.length)), this.tableEl = o;
		let c = document.createElement("caption");
		c.id = this.captionId, c.className = "cmm-sr-only", c.textContent = this.config.emptyMessage === void 0 ? `Data table with ${String(this.rows.length)} rows and ${String(this.columns.length)} columns. Use arrow keys to navigate.` : `Data table. ${String(this.rows.length)} rows, ${String(this.columns.length)} columns. Use arrow keys to navigate.`, o.appendChild(c);
		let l = document.createElement("thead");
		l.className = "cmm-data-table__head";
		let u = document.createElement("tr");
		u.setAttribute("role", "row");
		for (let t = 0; t < this.columns.length; t++) {
			let n = this.columns[t];
			if (n === void 0) continue;
			let r = document.createElement("th");
			r.className = "cmm-data-table__header", r.setAttribute("role", "columnheader"), r.setAttribute("scope", "col"), r.setAttribute("aria-colindex", String(t + 1)), n.width !== void 0 && (r.style.width = n.width), n.className !== void 0 && r.classList.add(n.className), n.sortable === !0 ? (r.classList.add("cmm-data-table__header--sortable"), r.setAttribute("aria-sort", this.getSortLabel(n.key)), r.setAttribute("tabindex", "0"), r.innerHTML = `${e(n.label)} ${this.buildSortIcon(n.key)}`, r.addEventListener("click", () => {
				this.handleSort(n.key);
			}), r.addEventListener("keydown", (e) => {
				(e.key === s.ENTER || e.key === s.SPACE) && (e.preventDefault(), this.handleSort(n.key));
			})) : r.textContent = n.label, this.sortState !== null && this.sortState.key === n.key && r.classList.add("cmm-data-table__cell--sorted"), u.appendChild(r);
		}
		l.appendChild(u), o.appendChild(l);
		let f = document.createElement("tbody");
		if (f.className = "cmm-data-table__body", a.length === 0) {
			let e = document.createElement("tr");
			e.setAttribute("role", "row");
			let t = document.createElement("td");
			t.className = "cmm-data-table__empty", t.colSpan = this.columns.length, t.setAttribute("role", "gridcell"), t.textContent = this.config.emptyMessage ?? "No data available", e.appendChild(t), f.appendChild(e);
		} else {
			let e = n === void 0 ? 0 : this.currentPage * n.pageSize;
			for (let t = 0; t < a.length; t++) {
				let n = a[t];
				if (n === void 0) continue;
				let r = document.createElement("tr");
				r.className = "cmm-data-table__row", r.setAttribute("role", "row"), r.setAttribute("aria-rowindex", String(e + t + 1));
				let i = e + t;
				this.config.onRowClick !== void 0 && (r.classList.add("cmm-data-table__row--clickable"), r.style.cursor = "pointer", r.addEventListener("click", () => {
					this.config.onRowClick?.(n, i);
				})), this.config.onRowContext !== void 0 && r.addEventListener("contextmenu", (e) => {
					this.config.onRowContext?.(n, i, e);
				});
				for (let e = 0; e < this.columns.length; e++) {
					let i = this.columns[e];
					if (i === void 0) continue;
					let a = document.createElement("td");
					a.className = "cmm-data-table__cell", a.setAttribute("role", "gridcell"), a.setAttribute("aria-colindex", String(e + 1)), a.setAttribute("tabindex", t === this.focusedRow && e === this.focusedCol ? "0" : "-1"), i.className !== void 0 && a.classList.add(i.className), this.sortState !== null && this.sortState.key === i.key && a.classList.add("cmm-data-table__cell--sorted");
					let o = n[e], s = i.renderer ?? "text", c = {};
					i.badgeMap !== void 0 && (c.badgeMap = i.badgeMap), i.format !== void 0 && (c.format = i.format), a.innerHTML = d(o, s, c), r.appendChild(a);
				}
				f.appendChild(r);
			}
		}
		o.appendChild(f), o.addEventListener("keydown", (e) => {
			this.handleKeyDown(e);
		}), t.appendChild(o), n !== void 0 && (n.position === void 0 || n.position === "bottom" || n.position === "both") && t.appendChild(this.buildPagination("bottom")), this.container.appendChild(t);
	}
	buildPagination(e) {
		let t = document.createElement("nav");
		t.className = "cmm-data-table__pagination", t.setAttribute("role", "navigation"), t.setAttribute("aria-label", `Table pagination ${e}`);
		let n = this.getTotalPages(), r = document.createElement("span");
		r.className = "cmm-data-table__pagination-info", r.setAttribute("aria-live", "polite"), r.textContent = `Page ${String(this.currentPage + 1)} of ${String(n)}`, t.appendChild(r);
		let i = document.createElement("button");
		i.className = "cmm-data-table__pagination-btn", i.type = "button", i.textContent = "Previous", i.disabled = this.currentPage === 0, i.setAttribute("aria-label", "Go to previous page"), this.currentPage === 0 && i.setAttribute("aria-disabled", "true"), i.addEventListener("click", () => {
			this.currentPage > 0 && (this.currentPage--, this.focusedRow = 0, this.focusedCol = 0, this.render(), this.announceUpdate(`Page ${String(this.currentPage + 1)} of ${String(n)}`));
		}), t.appendChild(i);
		let a = document.createElement("button");
		return a.className = "cmm-data-table__pagination-btn", a.type = "button", a.textContent = "Next", a.disabled = this.currentPage >= n - 1, a.setAttribute("aria-label", "Go to next page"), this.currentPage >= n - 1 && a.setAttribute("aria-disabled", "true"), a.addEventListener("click", () => {
			this.currentPage < n - 1 && (this.currentPage++, this.focusedRow = 0, this.focusedCol = 0, this.render(), this.announceUpdate(`Page ${String(this.currentPage + 1)} of ${String(n)}`));
		}), t.appendChild(a), t;
	}
	buildExportBar() {
		let e = document.createElement("div");
		e.className = "cmm-data-table__export", e.setAttribute("role", "toolbar"), e.setAttribute("aria-label", "Export options");
		let t = this.config.exportFormats ?? [];
		for (let n of t) {
			let t = document.createElement("button");
			switch (t.className = "cmm-data-table__export-btn", t.type = "button", n) {
				case "csv":
					t.textContent = "Export CSV", t.setAttribute("aria-label", "Export data as CSV file"), t.addEventListener("click", () => {
						let e = p(this.columns, this.rows), t = new Blob([e], { type: "text/csv" }), n = URL.createObjectURL(t), r = document.createElement("a");
						r.href = n, r.download = "export.csv", r.click(), URL.revokeObjectURL(n), this.announceUpdate("CSV file downloaded");
					});
					break;
				case "json":
					t.textContent = "Export JSON", t.setAttribute("aria-label", "Export data as JSON file"), t.addEventListener("click", () => {
						let e = m(this.columns, this.rows), t = new Blob([e], { type: "application/json" }), n = URL.createObjectURL(t), r = document.createElement("a");
						r.href = n, r.download = "export.json", r.click(), URL.revokeObjectURL(n), this.announceUpdate("JSON file downloaded");
					});
					break;
				case "clipboard":
					t.textContent = "Copy to Clipboard", t.setAttribute("aria-label", "Copy data to clipboard"), t.addEventListener("click", () => {
						h(p(this.columns, this.rows)).then(() => {
							this.announceUpdate("Data copied to clipboard");
						});
					});
					break;
			}
			e.appendChild(t);
		}
		return e;
	}
};
//#endregion
export { _ as t };

//# sourceMappingURL=data-table-YEkMufAM.js.map