//#region src/renderers/xlsx.ts
/**
* XLSX renderer — lazy-loads ExcelJS on first use.
* Extracts tables from the document and renders each as a worksheet.
* Non-table content (headings, text) becomes header rows.
*/
function resolveColumn(col) {
	return typeof col === "string" ? { header: col } : col;
}
function getTextContent(children) {
	return children.map((c) => typeof c === "string" ? c : getTextContent(c.children)).join("");
}
/** Walk the tree and group content into sheets (one per page, or one global). */
function extractSheets(node) {
	const sheets = [];
	let currentSheet = {
		name: "Sheet 1",
		headings: [],
		tables: []
	};
	function walk(n) {
		switch (n.type) {
			case "document":
				walkChildren(n);
				break;
			case "page":
				pushCurrentSheet();
				currentSheet = {
					name: `Sheet ${sheets.length + 1}`,
					headings: [],
					tables: []
				};
				walkChildren(n);
				break;
			case "heading":
				addHeading(n);
				break;
			case "table":
				currentSheet.tables.push(n);
				break;
			default: walkChildren(n);
		}
	}
	function walkChildren(n) {
		for (const child of n.children) if (typeof child !== "string") walk(child);
	}
	function pushCurrentSheet() {
		if (currentSheet.tables.length > 0 || currentSheet.headings.length > 0) sheets.push(currentSheet);
	}
	function addHeading(n) {
		const text = getTextContent(n.children);
		currentSheet.headings.push(text);
		if (currentSheet.headings.length === 1) currentSheet.name = text.slice(0, 31);
	}
	walk(node);
	pushCurrentSheet();
	return sheets;
}
/** Parse a cell value, handling currencies, percentages, and plain numbers. */
function parseCellValue(value) {
	if (value == null) return "";
	if (typeof value === "number") return value;
	const trimmed = value.trim();
	if (/^-?\d+(\.\d+)?%$/.test(trimmed)) return Number.parseFloat(trimmed) / 100;
	if (trimmed.match(/^-?\$[\d,]+(\.\d+)?$/)) return Number.parseFloat(trimmed.replace(/[$,]/g, ""));
	const plainNum = Number(trimmed.replace(/,/g, ""));
	if (!Number.isNaN(plainNum) && /^-?[\d,]+(\.\d+)?$/.test(trimmed)) return plainNum;
	return value;
}
/** Get ExcelJS number format string for a value. */
function getCellFormat(originalValue) {
	if (typeof originalValue !== "string") return void 0;
	const trimmed = originalValue.trim();
	if (/^-?\d+(\.\d+)?%$/.test(trimmed)) return "0.00%";
	if (/^-?\$/.test(trimmed)) return "$#,##0.00";
}
/** Map alignment string to ExcelJS horizontal alignment. */
function mapAlignment(align) {
	if (align === "left" || align === "center" || align === "right") return align;
}
/** Thin border style for ExcelJS. */
function thinBorder() {
	return {
		style: "thin",
		color: { argb: "FFDDDDDD" }
	};
}
/** Apply header styling to a cell. */
function styleHeaderCell(cell, col, hs, bordered) {
	cell.value = col.header;
	cell.font = {
		bold: true,
		color: { argb: hs?.color?.replace("#", "FF") ?? "FF000000" }
	};
	if (hs?.background) cell.fill = {
		type: "pattern",
		pattern: "solid",
		fgColor: { argb: hs.background.replace("#", "FF") }
	};
	cell.alignment = { horizontal: mapAlignment(col.align) ?? "left" };
	if (bordered) cell.border = {
		top: thinBorder(),
		bottom: thinBorder(),
		left: thinBorder(),
		right: thinBorder()
	};
}
/** Apply data cell value and styling. */
function styleDataCell(cell, rawValue, col, striped, isOddRow, bordered) {
	cell.value = parseCellValue(rawValue);
	const fmt = getCellFormat(rawValue);
	if (fmt) cell.numFmt = fmt;
	cell.alignment = { horizontal: mapAlignment(col.align) ?? "left" };
	if (striped && isOddRow) cell.fill = {
		type: "pattern",
		pattern: "solid",
		fgColor: { argb: "FFF9F9F9" }
	};
	if (bordered) cell.border = {
		top: thinBorder(),
		bottom: thinBorder(),
		left: thinBorder(),
		right: thinBorder()
	};
}
/** Render a single table node into the worksheet starting at the given row. Returns the next row number. */
function renderTable(ws, tableNode, startRow) {
	let rowNum = startRow;
	const columns = (tableNode.props.columns ?? []).map(resolveColumn);
	const rows = tableNode.props.rows ?? [];
	const hs = tableNode.props.headerStyle;
	const bordered = tableNode.props.bordered ?? false;
	if (tableNode.props.caption) {
		const captionCell = ws.getRow(rowNum).getCell(1);
		captionCell.value = tableNode.props.caption;
		captionCell.font = {
			italic: true,
			size: 10
		};
		rowNum++;
	}
	const headerRow = ws.getRow(rowNum);
	for (let i = 0; i < columns.length; i++) {
		const col = columns[i];
		if (!col) continue;
		styleHeaderCell(headerRow.getCell(i + 1), col, hs, bordered);
	}
	rowNum++;
	for (let r = 0; r < rows.length; r++) {
		const dataRow = ws.getRow(rowNum);
		for (let c = 0; c < columns.length; c++) {
			const col = columns[c];
			if (!col) continue;
			styleDataCell(dataRow.getCell(c + 1), rows[r]?.[c], col, tableNode.props.striped ?? false, r % 2 === 1, bordered);
		}
		rowNum++;
	}
	return rowNum + 1;
}
/** Auto-fit column widths based on content. */
function autoFitColumns(ws) {
	for (const col of ws.columns) {
		let maxLen = 10;
		col.eachCell?.({ includeEmpty: false }, (cell) => {
			const len = String(cell.value ?? "").length;
			if (len > maxLen) maxLen = len;
		});
		col.width = Math.min(maxLen + 2, 50);
	}
}
const xlsxRenderer = { async render(node, _options) {
	let ExcelJS;
	try {
		ExcelJS = await import("./exceljs-BYETsesT.js");
	} catch {
		throw new Error("[@pyreon/document] XLSX renderer requires \"exceljs\" package. Install it: bun add exceljs");
	}
	const workbook = new ExcelJS.default.Workbook();
	workbook.creator = node.props.author ?? "";
	workbook.title = node.props.title ?? "";
	const sheets = extractSheets(node);
	if (sheets.length === 0) workbook.addWorksheet("Sheet 1");
	for (const sheet of sheets) {
		const ws = workbook.addWorksheet(sheet.name);
		let rowNum = 1;
		for (const heading of sheet.headings) {
			const row = ws.getRow(rowNum);
			row.getCell(1).value = heading;
			row.getCell(1).font = {
				bold: true,
				size: 14
			};
			rowNum++;
		}
		if (sheet.headings.length > 0) rowNum++;
		for (const tableNode of sheet.tables) rowNum = renderTable(ws, tableNode, rowNum);
		autoFitColumns(ws);
	}
	const buffer = await workbook.xlsx.writeBuffer();
	return new Uint8Array(buffer);
} };

//#endregion
export { xlsxRenderer };
//# sourceMappingURL=xlsx-Cvu4LBNy.js.map