'use strict';

var cloneDeep = require('lodash/cloneDeep');
var TraversalTracker = require('./traversalTracker');
var DocPreprocessor = require('./docPreprocessor');
var DocMeasure = require('./docMeasure');
var DocumentContext = require('./documentContext');
var PageElementWriter = require('./pageElementWriter');
var ColumnCalculator = require('./columnCalculator');
var TableProcessor = require('./tableProcessor');
var Line = require('./line');
var isString = require('./helpers').isString;
var isArray = require('./helpers').isArray;
var isUndefined = require('./helpers').isUndefined;
var isNull = require('./helpers').isNull;
var pack = require('./helpers').pack;
var offsetVector = require('./helpers').offsetVector;
var fontStringify = require('./helpers').fontStringify;
var getNodeId = require('./helpers').getNodeId;
var isFunction = require('./helpers').isFunction;
var TextTools = require('./textTools');
var StyleContextStack = require('./styleContextStack');
var isNumber = require('./helpers').isNumber;

var footerBreak = false;
var testTracker;
var testWriter;
var testVerticalAlignStack = [];
var testResult = false;
var currentLayoutBuilder;

function addAll(target, otherArray) {
	if (!isArray(target) || !isArray(otherArray) || otherArray.length === 0) {
		return;
	}

	otherArray.forEach(function (item) {
		target.push(item);
	});
}

/**
 * Creates an instance of LayoutBuilder - layout engine which turns document-definition-object
 * into a set of pages, lines, inlines and vectors ready to be rendered into a PDF
 *
 * @param {Object} pageSize - an object defining page width and height
 * @param {Object} pageMargins - an object defining top, left, right and bottom margins
 */
function LayoutBuilder(pageSize, pageMargins, imageMeasure, svgMeasure) {
	this.pageSize = pageSize;
	this.pageMargins = pageMargins;
	this.tracker = new TraversalTracker();
	this.imageMeasure = imageMeasure;
	this.svgMeasure = svgMeasure;
	this.tableLayouts = {};
	this.nestedLevel = 0;
	this.verticalAlignItemStack = [];
	this.heightHeaderAndFooter = {};

	this._footerColumnGuides = null;
  	this._footerGapOption = null;
}

LayoutBuilder.prototype.registerTableLayouts = function (tableLayouts) {
	this.tableLayouts = pack(this.tableLayouts, tableLayouts);
};

/**
 * Executes layout engine on document-definition-object and creates an array of pages
 * containing positioned Blocks, Lines and inlines
 *
 * @param {Object} docStructure document-definition-object
 * @param {Object} fontProvider font provider
 * @param {Object} styleDictionary dictionary with style definitions
 * @param {Object} defaultStyle default style definition
 * @return {Array} an array of pages
 */
LayoutBuilder.prototype.layoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark, pageBreakBeforeFct) {

	function addPageBreaksIfNecessary(linearNodeList, pages) {

		if (!isFunction(pageBreakBeforeFct)) {
			return false;
		}

		linearNodeList = linearNodeList.filter(function (node) {
			return node.positions.length > 0;
		});

		linearNodeList.forEach(function (node) {
			var nodeInfo = {};
			[
				'id', 'text', 'ul', 'ol', 'table', 'image', 'qr', 'canvas', 'svg', 'columns', 'layers',
				'headlineLevel', 'style', 'pageBreak', 'pageOrientation',
				'width', 'height'
			].forEach(function (key) {
				if (node[key] !== undefined) {
					nodeInfo[key] = node[key];
				}
			});
			nodeInfo.startPosition = node.positions[0];
			nodeInfo.pageNumbers = Array.from(new Set(node.positions.map(function (node) { return node.pageNumber; })));
			nodeInfo.pages = pages.length;
			nodeInfo.stack = isArray(node.stack);
			nodeInfo.layers = isArray(node.layers);

			node.nodeInfo = nodeInfo;
		});

		for (var index = 0; index < linearNodeList.length; index++) {
			var node = linearNodeList[index];
			if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
				node.pageBreakCalculated = true;
				var pageNumber = node.nodeInfo.pageNumbers[0];
				var followingNodesOnPage = [];
				var nodesOnNextPage = [];
				var previousNodesOnPage = [];
				if (pageBreakBeforeFct.length > 1) {
					for (var ii = index + 1, l = linearNodeList.length; ii < l; ii++) {
						if (linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
							followingNodesOnPage.push(linearNodeList[ii].nodeInfo);
						}
						if (pageBreakBeforeFct.length > 2 && linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber + 1) > -1) {
							nodesOnNextPage.push(linearNodeList[ii].nodeInfo);
						}
					}
				}
				if (pageBreakBeforeFct.length > 3) {
					for (var jj = 0; jj < index; jj++) {
						if (linearNodeList[jj].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
							previousNodesOnPage.push(linearNodeList[jj].nodeInfo);
						}
					}
				}
				if (pageBreakBeforeFct(node.nodeInfo, followingNodesOnPage, nodesOnNextPage, previousNodesOnPage)) {
					node.pageBreak = 'before';
					return true;
				}
			}
		}

		return false;
	}

	this.docPreprocessor = new DocPreprocessor();
	this.docMeasure = new DocMeasure(fontProvider, styleDictionary, defaultStyle, this.imageMeasure, this.svgMeasure, this.tableLayouts, images);


	function resetXYs(result) {
		result.linearNodeList.forEach(function (node) {
			node.resetXY();
		});
	}

	var result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
	while (addPageBreaksIfNecessary(result.linearNodeList, result.pages)) {
		resetXYs(result);
		result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
	}

	return result.pages;
};

LayoutBuilder.prototype.tryLayoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark) {
	footerBreak = false;

	this.verticalAlignItemStack = this.verticalAlignItemStack || [];
	this.linearNodeList = [];
	this.writer = new PageElementWriter(
		new DocumentContext(this.pageSize, this.pageMargins, this._footerGapOption), this.tracker);

	this.heightHeaderAndFooter = this.addHeadersAndFooters(header, footer) || {};
	if (!isUndefined(this.heightHeaderAndFooter.header)) {
		this.pageMargins.top = this.heightHeaderAndFooter.header + 1;
	}

	if (isArray(docStructure) && docStructure[2] && isArray(docStructure[2]) && docStructure[2][0] && docStructure[2][0].remark) {
		var tableRemark = docStructure[2][0].remark;
		var remarkLabel = docStructure[2][0];
		var remarkDetail = docStructure[2][1] && docStructure[2][1].text;

		docStructure[2].splice(0, 1);
		if (docStructure[2].length > 0) {
			docStructure[2].splice(0, 1);
		}

		var labelRow = [];
		var detailRow = [];

		labelRow.push(remarkLabel);
		detailRow.push({ remarktest: true, text: remarkDetail });

		tableRemark.table.body.push(labelRow);
		tableRemark.table.body.push(detailRow);

		tableRemark.table.headerRows = 1;

		docStructure[2].push(tableRemark);
	}

	this.linearNodeList = [];
	docStructure = this.docPreprocessor.preprocessDocument(docStructure);
	docStructure = this.docMeasure.measureDocument(docStructure);

	this.verticalAlignItemStack = [];
	this.writer = new PageElementWriter(
		new DocumentContext(this.pageSize, this.pageMargins, this._footerGapOption), this.tracker);

	var _this = this;
	this.writer.context().tracker.startTracking('pageAdded', function () {
		_this.addBackground(background);
	});

	this.addBackground(background);
	this.processNode(docStructure);
	this.addHeadersAndFooters(header, footer,
		(this.heightHeaderAndFooter.header || 0) + 1,
		(this.heightHeaderAndFooter.footer || 0) + 1);
	if (watermark != null) {
		this.addWatermark(watermark, fontProvider, defaultStyle);
	}

	return { pages: this.writer.context().pages, linearNodeList: this.linearNodeList };
};

LayoutBuilder.prototype.applyFooterGapOption = function(opt) {
    if (opt === true) {
        opt = { enabled: true };
    }
	
    if (!opt) return;

    if (typeof opt !== 'object') {
        this._footerGapOption = { enabled: true, forcePageBreakForAllRows: false };
        return;
    }

    this._footerGapOption = {
        enabled: opt.enabled !== false,
        minRowHeight: typeof opt.minRowHeight === 'number' ? opt.minRowHeight : undefined, // Optional fallback - system auto-calculates from cell content if not provided
        forcePageBreakForAllRows: opt.forcePageBreakForAllRows === true, // Force page break for all rows (not just inline images)
        columns: opt.columns ? {
            widths: Array.isArray(opt.columns.widths) ? opt.columns.widths.slice() : undefined,
            widthLength: opt.columns.widths.length || 0,
            stops: Array.isArray(opt.columns.stops) ? opt.columns.stops.slice() : undefined,
            style: opt.columns.style ? Object.assign({}, opt.columns.style) : {},
            includeOuter: opt.columns.includeOuter !== false
        } : null
    };
};

LayoutBuilder.prototype.addBackground = function (background) {
	var backgroundGetter = isFunction(background) ? background : function () {
		return background;
	};

	var context = this.writer.context();
	var pageSize = context.getCurrentPage().pageSize;

	var pageBackground = backgroundGetter(context.page + 1, pageSize);

	if (pageBackground) {
		this.writer.beginUnbreakableBlock(pageSize.width, pageSize.height);
		pageBackground = this.docPreprocessor.preprocessDocument(pageBackground);
		this.processNode(this.docMeasure.measureDocument(pageBackground));
		this.writer.commitUnbreakableBlock(0, 0);
		context.backgroundLength[context.page] += pageBackground.positions.length;
	}
};

LayoutBuilder.prototype.addStaticRepeatable = function (headerOrFooter, sizeFunction) {
	return this.addDynamicRepeatable(function () {
		return JSON.parse(JSON.stringify(headerOrFooter)); // copy to new object
	}, sizeFunction);
};

LayoutBuilder.prototype.addDynamicRepeatable = function (nodeGetter, sizeFunction) {
	var pages = this.writer.context().pages;
	var measuredHeight;

	for (var pageIndex = 0, l = pages.length; pageIndex < l; pageIndex++) {
		this.writer.context().page = pageIndex;

		var node = nodeGetter(pageIndex + 1, l, this.writer.context().pages[pageIndex].pageSize);

		if (node) {
			var sizes = sizeFunction(this.writer.context().getCurrentPage().pageSize, this.pageMargins);
			this.writer.beginUnbreakableBlock(sizes.width, sizes.height);
			node = this.docPreprocessor.preprocessDocument(node);
			this.processNode(this.docMeasure.measureDocument(node));
			this.writer.commitUnbreakableBlock(sizes.x, sizes.y);
			if (!isUndefined(node._height)) {
				measuredHeight = node._height;
			}
		}
	}

	return measuredHeight;
};

LayoutBuilder.prototype.addHeadersAndFooters = function (header, footer, headerHeight, footerHeight) {
	var measured = { header: undefined, footer: undefined };

	var headerSizeFct = function (pageSize) {
		var effectiveHeight = headerHeight;
		if (isUndefined(effectiveHeight)) {
			effectiveHeight = pageSize.height;
		}
		return {
			x: 0,
			y: 0,
			width: pageSize.width,
			height: effectiveHeight
		};
	};

	var footerSizeFct = function (pageSize) {
		var effectiveHeight = footerHeight;
		if (isUndefined(effectiveHeight)) {
			effectiveHeight = pageSize.height;
		}
		return {
			x: 0,
			y: pageSize.height - effectiveHeight,
			width: pageSize.width,
			height: effectiveHeight
		};
	};

	if (this._footerGapOption && !this.writer.context()._footerGapOption) {
        this.writer.context()._footerGapOption = this._footerGapOption;
    }

	if (isFunction(header)) {
		measured.header = this.addDynamicRepeatable(header, headerSizeFct);
	} else if (header) {
		measured.header = this.addStaticRepeatable(header, headerSizeFct);
	}

	if (isFunction(footer)) {
		measured.footer = this.addDynamicRepeatable(footer, footerSizeFct);
	} else if (footer) {
		measured.footer = this.addStaticRepeatable(footer, footerSizeFct);
	}

	return measured;
};

LayoutBuilder.prototype.addWatermark = function (watermark, fontProvider, defaultStyle) {
	if (isString(watermark)) {
		watermark = { 'text': watermark };
	}

	if (!watermark.text) { // empty watermark text
		return;
	}

	var pages = this.writer.context().pages;
	for (var i = 0, l = pages.length; i < l; i++) {
		pages[i].watermark = getWatermarkObject({ ...watermark }, pages[i].pageSize, fontProvider, defaultStyle);
	}

	function getWatermarkObject(watermark, pageSize, fontProvider, defaultStyle) {
		watermark.font = watermark.font || defaultStyle.font || 'Roboto';
		watermark.fontSize = watermark.fontSize || 'auto';
		watermark.color = watermark.color || 'black';
		watermark.opacity = isNumber(watermark.opacity) ? watermark.opacity : 0.6;
		watermark.bold = watermark.bold || false;
		watermark.italics = watermark.italics || false;
		watermark.angle = !isUndefined(watermark.angle) && !isNull(watermark.angle) ? watermark.angle : null;

		if (watermark.angle === null) {
			watermark.angle = Math.atan2(pageSize.height, pageSize.width) * -180 / Math.PI;
		}

		if (watermark.fontSize === 'auto') {
			watermark.fontSize = getWatermarkFontSize(pageSize, watermark, fontProvider);
		}

		var watermarkObject = {
			text: watermark.text,
			font: fontProvider.provideFont(watermark.font, watermark.bold, watermark.italics),
			fontSize: watermark.fontSize,
			color: watermark.color,
			opacity: watermark.opacity,
			angle: watermark.angle
		};

		watermarkObject._size = getWatermarkSize(watermark, fontProvider);

		return watermarkObject;
	}

	function getWatermarkSize(watermark, fontProvider) {
		var textTools = new TextTools(fontProvider);
		var styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });

		styleContextStack.push({
			fontSize: watermark.fontSize
		});

		var size = textTools.sizeOfString(watermark.text, styleContextStack);
		var rotatedSize = textTools.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);

		return { size: size, rotatedSize: rotatedSize };
	}

	function getWatermarkFontSize(pageSize, watermark, fontProvider) {
		var textTools = new TextTools(fontProvider);
		var styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });
		var rotatedSize;

		/**
		 * Binary search the best font size.
		 * Initial bounds [0, 1000]
		 * Break when range < 1
		 */
		var a = 0;
		var b = 1000;
		var c = (a + b) / 2;
		while (Math.abs(a - b) > 1) {
			styleContextStack.push({
				fontSize: c
			});
			rotatedSize = textTools.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
			if (rotatedSize.width > pageSize.width) {
				b = c;
				c = (a + b) / 2;
			} else if (rotatedSize.width < pageSize.width) {
				if (rotatedSize.height > pageSize.height) {
					b = c;
					c = (a + b) / 2;
				} else {
					a = c;
					c = (a + b) / 2;
				}
			}
			styleContextStack.pop();
		}
		/*
		 End binary search
		 */
		return c;
	}
};

function decorateNode(node) {
	var x = node.x, y = node.y;
	node.positions = [];

	if (isArray(node.canvas)) {
		node.canvas.forEach(function (vector) {
			var x = vector.x, y = vector.y, x1 = vector.x1, y1 = vector.y1, x2 = vector.x2, y2 = vector.y2;
			vector.resetXY = function () {
				vector.x = x;
				vector.y = y;
				vector.x1 = x1;
				vector.y1 = y1;
				vector.x2 = x2;
				vector.y2 = y2;
			};
		});
	}

	node.resetXY = function () {
		node.x = x;
		node.y = y;
		if (isArray(node.canvas)) {
			node.canvas.forEach(function (vector) {
				vector.resetXY();
			});
		}
	};
}

LayoutBuilder.prototype.processNode = function (node) {
	var self = this;

	if (footerBreak && (node.footerBreak || node.footer)) {
		return;
	}

	if (node && node.unbreakable && node.summary && node.table && node.table.body &&
		node.table.body[0] && node.table.body[0][0] && node.table.body[0][0].summaryBreak) {
		testTracker = new TraversalTracker();
		testWriter = new PageElementWriter(self.writer.context(), testTracker);
		testVerticalAlignStack = self.verticalAlignItemStack.slice();
		currentLayoutBuilder = self;
		testResult = false;
		var nodeForTest = cloneDeep(node);
		if (nodeForTest.table.body[0]) {
			nodeForTest.table.body[0].splice(0, 1);
		}
		processNode_test(nodeForTest);
		currentLayoutBuilder = null;
		if (testResult && node.table.body[0]) {
			node.table.body[0].splice(0, 1);
		}
	}

	this.linearNodeList.push(node);
	decorateNode(node);

	var prevTop = self.writer.context().getCurrentPosition().top;

	applyMargins(function () {
		var unbreakable = node.unbreakable;
		if (unbreakable) {
			self.writer.beginUnbreakableBlock();
		}

		var absPosition = node.absolutePosition;
		if (absPosition) {
			self.writer.context().beginDetachedBlock();
			self.writer.context().moveTo(absPosition.x || 0, absPosition.y || 0);
		}

		var relPosition = node.relativePosition;
		if (relPosition) {
			self.writer.context().beginDetachedBlock();
			self.writer.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
		}

		var verticalAlignBegin;
		if (node.verticalAlign) {
			verticalAlignBegin = self.writer.beginVerticalAlign(node.verticalAlign);
		}

		if (node.stack) {
			// Handle _footerGapOption for breakable stacks
			var footerGapEnabled = !unbreakable && node.footer && node._footerGapOption && node._footerGapOption.enabled;
			var preRenderState = null;

			if (footerGapEnabled) {
				var ctx = self.writer.context();
				var currentPage = ctx.getCurrentPage();
				preRenderState = {
					startY: ctx.y,
					startPage: ctx.page,
					availableHeight: ctx.availableHeight,
					itemCount: currentPage ? currentPage.items.length : 0
				};
			}

			// Process the stack
			self.processVerticalContainer(node);

			// Post-render repositioning
			if (footerGapEnabled && preRenderState) {
				var ctx = self.writer.context();

				// Only reposition if on same page (single-page content)
				if (ctx.page === preRenderState.startPage) {
					var renderedHeight = ctx.y - preRenderState.startY;
					var gapHeight = preRenderState.availableHeight - renderedHeight;

					if (gapHeight > 0) {
						var currentPage = ctx.getCurrentPage();

						// SINGLE-PAGE: Draw guide lines in the gap area
						var gapTopY = preRenderState.startY;
						var colSpec = node._footerGapOption.columns || self._footerGapOption.columns || null;
						if (colSpec) {
							var rawWidths = colSpec.content.vLines || [];
							if (rawWidths && rawWidths.length > 1) {
								var style = (colSpec.style || {});
								var lw = style.lineWidth != null ? style.lineWidth : 0.5;
								var lc = style.color || '#000000';
								var dashCfg = style.dash;
								var includeOuter = colSpec.includeOuter !== false;
								var startIndex = includeOuter ? 0 : 1;
								var endIndex = includeOuter ? rawWidths.length : rawWidths.length - 1;

								for (var ci = startIndex; ci < endIndex; ci++) {
									var xGuide = ctx.x + rawWidths[ci] - 0.25;
									currentPage.items.push({
										type: 'vector',
										item: {
											type: 'line',
											x1: xGuide,
											y1: gapTopY,
											x2: xGuide,
											y2: gapTopY + gapHeight,
											lineWidth: lw,
											lineColor: lc,
											dash: dashCfg ? {
												length: dashCfg.length,
												space: dashCfg.space != null ? dashCfg.space : dashCfg.gap
											} : undefined,
											_footerGuideLine: true
										}
									});
								}
							}
						}

						// Reposition only items that belong to footer stack content
						// Iterate ALL items (backgrounds are inserted at lower indices, not appended)
						// Filter by Y position to exclude non-footer items
						for (var i = 0; i < currentPage.items.length; i++) {
							var item = currentPage.items[i];

							// Skip the guide lines we just added (they're already positioned correctly)
							if (item.item && item.item._footerGuideLine) {
								continue;
							}

							// Get the item's starting Y position
							var itemStartY = null;
							if (item.item && typeof item.item.y1 === 'number') {
								itemStartY = item.item.y1;
							} else if (item.item && typeof item.item.y === 'number') {
								itemStartY = item.item.y;
							}

							// Only reposition items that START at or after footer stack's Y position
							// This excludes outer table border lines that extend from earlier rows
							if (itemStartY !== null && itemStartY < preRenderState.startY) {
								continue;
							}

							// Reposition this item
							if (item.item && typeof item.item.y === 'number') {
								item.item.y += gapHeight;
							}
							if (item.item && typeof item.item.y1 === 'number') {
								item.item.y1 += gapHeight;
							}
							if (item.item && typeof item.item.y2 === 'number') {
								item.item.y2 += gapHeight;
							}
							// Handle polylines (points array)
							if (item.item && item.item.points && Array.isArray(item.item.points)) {
								for (var pi = 0; pi < item.item.points.length; pi++) {
									if (typeof item.item.points[pi].y === 'number') {
										item.item.points[pi].y += gapHeight;
									}
								}
							}
						}
						ctx.moveDown(gapHeight);
					}
				} else {
					// MULTI-PAGE: Process ALL pages from startPage+1 to current page
					// Only move FOOTER items to bottom, keep remark at top
					var pages = ctx.pages;
					var pageMargins = ctx.pageMargins;

					// Helper function to recursively find node with _isFooterTable
					function findFooterTableNode(n) {
						if (!n) return null;
						if (n._isFooterTable) return n;
						if (n.stack && Array.isArray(n.stack)) {
							for (var i = 0; i < n.stack.length; i++) {
								var found = findFooterTableNode(n.stack[i]);
								if (found) return found;
							}
						}
						if (Array.isArray(n)) {
							for (var i = 0; i < n.length; i++) {
								var found = findFooterTableNode(n[i]);
								if (found) return found;
							}
						}
						return null;
					}

					// Find footer table node to get its height
					var footerStackItem = null;
					if (node.stack && node.stack.length > 0) {
						for (var si = node.stack.length - 1; si >= 0; si--) {
							var found = findFooterTableNode(node.stack[si]);
							if (found) {
								footerStackItem = node.stack[si];
								break;
							}
						}
					}

					var stackHeight = Math.abs((footerStackItem && footerStackItem._height) || 0);

					// Only process the LAST page where footer is located
					// Intermediate pages (remark only) should not be repositioned
					var pageIdx = ctx.page;
					if (pageIdx > preRenderState.startPage) {
						var page = pages[pageIdx];
						if (page && page.items && page.items.length > 0) {
							var pageHeight = page.pageSize.height;
							var bottomMargin = pageMargins.bottom;
							var pageBottom = pageHeight - bottomMargin;

							// Find footer start Y on this page (where footer items begin)
							// Use footerHeight to identify footer area from the bottom of content
							var contentBottom = 0;
							for (var i = 0; i < page.items.length; i++) {
								var item = page.items[i];
								var itemBottom = 0;
								if (item.item) {
									if (typeof item.item.y === 'number') {
										var h = item.item.h || item.item.height || 0;
										itemBottom = item.item.y + h;
									}
									if (typeof item.item.y2 === 'number' && item.item.y2 > itemBottom) {
										itemBottom = item.item.y2;
									}
								}
								if (itemBottom > contentBottom) {
									contentBottom = itemBottom;
								}
							}

							// Footer starts at contentBottom - footerHeight
							var stackStartY = contentBottom - stackHeight;

							// Calculate gap: how much to move footer down
							var gapHeight = pageBottom - contentBottom;
							if (gapHeight > 0) {
								// Only move items that are part of footer (Y >= footerStartY)
								for (var i = 0; i < page.items.length; i++) {
									var item = page.items[i];
									var itemY = null;
									if (item.item && typeof item.item.y1 === 'number') {
										itemY = item.item.y1;
									} else if (item.item && typeof item.item.y === 'number') {
										itemY = item.item.y;
									} else if (item.item && item.item.points && Array.isArray(item.item.points) && item.item.points.length > 0) {
										// For polylines, use the first point's Y
										itemY = item.item.points[0].y;
									}

									// Skip items above footer
									if (itemY === null || itemY < stackStartY) continue;

									// Don't move items that are near the top margin (table headers)
									// Use actual header height from repeatables instead of hardcoded threshold
									var repeatableHeaderHeight = 0;
									for (var ri = 0; ri < self.writer.repeatables.length; ri++) {
										repeatableHeaderHeight += self.writer.repeatables[ri].height;
									}
									var headerThreshold = pageMargins.top + repeatableHeaderHeight;
									if (itemY < headerThreshold) continue;

									// Move footer item down
									if (item.item && typeof item.item.y === 'number') {
										item.item.y += gapHeight;
									}
									if (item.item && typeof item.item.y1 === 'number') {
										item.item.y1 += gapHeight;
									}
									if (item.item && typeof item.item.y2 === 'number') {
										item.item.y2 += gapHeight;
									}
									// // Handle polylines (points array)
									if (item.item && item.item.points && Array.isArray(item.item.points)) {
										for (var pi = 0; pi < item.item.points.length; pi++) {
											if (typeof item.item.points[pi].y === 'number') {
												item.item.points[pi].y += gapHeight;
											}
										}
									}
								}
							}
						}
					}

					// Also update context for current page
					var lastPageGapHeight = ctx.availableHeight;
					if (lastPageGapHeight > 0) {
						ctx.moveDown(lastPageGapHeight);
					}
				}
			}
		} else if (node.layers) {
			self.processLayers(node);
		} else if (node.columns) {
			self.processColumns(node);
		} else if (node.ul) {
			self.processList(false, node);
		} else if (node.ol) {
			self.processList(true, node);
		} else if (node.table) {
			self.processTable(node);
		} else if (node.text !== undefined) {
			self.processLeaf(node);
		} else if (node.toc) {
			self.processToc(node);
		} else if (node.image) {
			self.processImage(node);
		} else if (node.svg) {
			self.processSVG(node);
		} else if (node.canvas) {
			self.processCanvas(node);
		} else if (node.qr) {
			self.processQr(node);
		} else if (!node._span) {
			throw new Error('Unrecognized document structure: ' + JSON.stringify(node, fontStringify));
		}

		if ((absPosition || relPosition) && !node.absoluteRepeatable) {
			self.writer.context().endDetachedBlock();
		}

		if (unbreakable) {
			if (node.footer) {
				footerBreak = self.writer.commitUnbreakableBlock(undefined, undefined, node.footer);
			} else {
				self.writer.commitUnbreakableBlock();
			}
		}

		if (node.verticalAlign) {
			var stackEntry = {
				begin: verticalAlignBegin,
				end: self.writer.endVerticalAlign(node.verticalAlign)
			};
			self.verticalAlignItemStack.push(stackEntry);
			node._verticalAlignIdx = self.verticalAlignItemStack.length - 1;
		}
	});

	node._height = self.writer.context().getCurrentPosition().top - prevTop;

	function applyMargins(callback) {
		var margin = node._margin;

		if (node.pageBreak === 'before') {
			self.writer.moveToNextPage(node.pageOrientation);
		}

		if (margin) {
			self.writer.context().moveDown(margin[1]);
			self.writer.context().addMargin(margin[0], margin[2]);
		}

		callback();

		if (margin) {
			self.writer.context().addMargin(-margin[0], -margin[2]);
			self.writer.context().moveDown(margin[3]);
		}

		if (node.pageBreak === 'after') {
			self.writer.moveToNextPage(node.pageOrientation);
		}
	}
};

// vertical container
LayoutBuilder.prototype.processVerticalContainer = function (node) {
	var self = this;
	node.stack.forEach(function (item) {
		self.processNode(item);
		addAll(node.positions, item.positions);

		//TODO: paragraph gap
	});
};

// layers
LayoutBuilder.prototype.processLayers = function(node) {
	var self = this;
	var ctxX = self.writer.context().x;
	var ctxY = self.writer.context().y;
	var maxX = ctxX;
	var maxY = ctxY;
	node.layers.forEach(function(item, i) {
	  self.writer.context().x = ctxX;
	  self.writer.context().y = ctxY;
	  self.processNode(item);
	  item._verticalAlignIdx = self.verticalAlignItemStack.length - 1;
	  addAll(node.positions, item.positions);
	  maxX = self.writer.context().x > maxX ? self.writer.context().x : maxX;
	  maxY = self.writer.context().y > maxY ? self.writer.context().y : maxY;
	});
	self.writer.context().x = maxX;
	self.writer.context().y = maxY;
};

// columns
LayoutBuilder.prototype.processColumns = function (columnNode) {
	this.nestedLevel++;
	var columns = columnNode.columns;
	var availableWidth = this.writer.context().availableWidth;
	var gaps = gapArray(columnNode._gap);

	if (gaps) {
		availableWidth -= (gaps.length - 1) * columnNode._gap;
	}

	ColumnCalculator.buildColumnWidths(columns, availableWidth);
	var result = this.processRow({
		marginX: columnNode._margin ? [columnNode._margin[0], columnNode._margin[2]] : [0, 0],
		cells: columns,
		widths: columns,
		gaps
	});
	addAll(columnNode.positions, result.positions);

	this.nestedLevel--;
	if (this.nestedLevel === 0) {
		this.writer.context().resetMarginXTopParent();
	}

	function gapArray(gap) {
		if (!gap) {
			return null;
		}

		var gaps = [];
		gaps.push(0);

		for (var i = columns.length - 1; i > 0; i--) {
			gaps.push(gap);
		}

		return gaps;
	}
};

/**
 * Searches for a cell in the same row that starts a rowspan and is positioned immediately before the current cell.
 * Alternatively, it finds a cell where the colspan initiating the rowspan extends to the cell just before the current one.
 *
 * @param {Array<object>} arr - An array representing cells in a row.
 * @param {number} i - The index of the current cell to search backward from.
 * @returns {object|null} The starting cell of the rowspan if found; otherwise, `null`.
 */
LayoutBuilder.prototype._findStartingRowSpanCell = function (arr, i) {
	var requiredColspan = 1;
	for (var index = i - 1; index >= 0; index--) {
		if (!arr[index]._span) {
			if (arr[index].rowSpan > 1 && (arr[index].colSpan || 1) === requiredColspan) {
				return arr[index];
			} else {
				return null;
			}
		}
		requiredColspan++;
	}
	return null;
};

/**
 * Retrieves a page break description for a specified page from a list of page breaks.
 *
 * @param {Array<object>} pageBreaks - An array of page break descriptions, each containing `prevPage` properties.
 * @param {number} page - The page number to find the associated page break for.
 * @returns {object|undefined} The page break description object for the specified page if found; otherwise, `undefined`.
 */
LayoutBuilder.prototype._getPageBreak = function (pageBreaks, page) {
	return pageBreaks.find(desc => desc.prevPage === page);
};

LayoutBuilder.prototype._getPageBreakListBySpan = function (tableNode, page, rowIndex) {
	if (!tableNode || !tableNode._breaksBySpan) {
		return null;
	}
	const breaksList = tableNode._breaksBySpan.filter(desc => desc.prevPage === page && rowIndex <= desc.rowIndexOfSpanEnd);

	var y = Number.MAX_VALUE,
		prevY = Number.MIN_VALUE;

	breaksList.forEach(b => {
		prevY = Math.max(b.prevY, prevY);
		y = Math.min(b.y, y);
	});

	return {
		prevPage: page,
		prevY: prevY,
		y: y
	};
};

LayoutBuilder.prototype._findSameRowPageBreakByRowSpanData = function (breaksBySpan, page, rowIndex) {
	if (!breaksBySpan) {
		return null;
	}
	return breaksBySpan.find(desc => desc.prevPage === page && rowIndex === desc.rowIndexOfSpanEnd);
};

LayoutBuilder.prototype._updatePageBreaksData = function (pageBreaks, tableNode, rowIndex) {
	Object.keys(tableNode._bottomByPage).forEach(p => {
		const page = Number(p);
		const pageBreak = this._getPageBreak(pageBreaks, page);
		if (pageBreak) {
			pageBreak.prevY = Math.max(pageBreak.prevY, tableNode._bottomByPage[page]);
		}
		if (tableNode._breaksBySpan && tableNode._breaksBySpan.length > 0) {
			const breaksBySpanList = tableNode._breaksBySpan.filter(pb => pb.prevPage === page && rowIndex <= pb.rowIndexOfSpanEnd);
			if (breaksBySpanList && breaksBySpanList.length > 0) {
				breaksBySpanList.forEach(b => {
					b.prevY = Math.max(b.prevY, tableNode._bottomByPage[page]);
				});
			}
		}
	});
};

/**
 * Resolves the Y-coordinates for a target object by comparing two break points.
 *
 * @param {object} break1 - The first break point with `prevY` and `y` properties.
 * @param {object} break2 - The second break point with `prevY` and `y` properties.
 * @param {object} target - The target object to be updated with resolved Y-coordinates.
 * @property {number} target.prevY - Updated to the maximum `prevY` value between `break1` and `break2`.
 * @property {number} target.y - Updated to the minimum `y` value between `break1` and `break2`.
 */
LayoutBuilder.prototype._resolveBreakY = function (break1, break2, target) {
	target.prevY = Math.max(break1.prevY, break2.prevY);
	target.y = Math.min(break1.y, break2.y);
};

LayoutBuilder.prototype._storePageBreakData = function (data, startsRowSpan, pageBreaks, tableNode) {
	var pageDesc;
	var pageDescBySpan;

	if (!startsRowSpan) {
		pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
		pageDescBySpan = this._getPageBreakListBySpan(tableNode, data.prevPage, data.rowIndex);
		if (!pageDesc) {
			pageDesc = Object.assign({}, data);
			pageBreaks.push(pageDesc);
		}

		if (pageDescBySpan) {
			this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
		}
		this._resolveBreakY(pageDesc, data, pageDesc);
	} else {
		var breaksBySpan = tableNode && tableNode._breaksBySpan || null;
		pageDescBySpan = this._findSameRowPageBreakByRowSpanData(breaksBySpan, data.prevPage, data.rowIndex);
		if (!pageDescBySpan) {
			pageDescBySpan = Object.assign({}, data, {
				rowIndexOfSpanEnd: data.rowIndex + data.rowSpan - 1
			});
			if (!tableNode._breaksBySpan) {
				tableNode._breaksBySpan = [];
			}
			tableNode._breaksBySpan.push(pageDescBySpan);
		}
		pageDescBySpan.prevY = Math.max(pageDescBySpan.prevY, data.prevY);
		pageDescBySpan.y = Math.min(pageDescBySpan.y, data.y);
		pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
		if (pageDesc) {
			this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
		}
	}
};

/**
 * Calculates the left offset for a column based on the specified gap values.
 *
 * @param {number} i - The index of the column for which the offset is being calculated.
 * @param {Array<number>} gaps - An array of gap values for each column.
 * @returns {number} The left offset for the column. Returns `gaps[i]` if it exists, otherwise `0`.
 */
LayoutBuilder.prototype._colLeftOffset = function (i, gaps) {
	if (gaps && gaps.length > i) {
		return gaps[i];
	}
	return 0;
};

/**
 * Checks if a cell or node contains an inline image.
 *
 * @param {object} node - The node to check for inline images.
 * @returns {boolean} True if the node contains an inline image; otherwise, false.
 */
 LayoutBuilder.prototype._containsInlineImage = function (node) {
	if (!node) {
		return false;
	}

	// Direct image node
	if (node.image) {
		return true;
	}


	// Check in table
	if (node.table && isArray(node.table.body)) {
		for (var r = 0; r < node.table.body.length; r++) {
			if (isArray(node.table.body[r])) {
				for (var c = 0; c < node.table.body[r].length; c++) {
					if (this._containsInlineImage(node.table.body[r][c])) {
						return true;
					}
				}
			}
		}
	}

	return false;
};


/**
 * Gets the maximum image height from cells in a row.
 *
 * @param {Array<object>} cells - Array of cell objects in a row.
 * @returns {number} The maximum image height found in the cells.
 */
 LayoutBuilder.prototype._getMaxImageHeight = function (cells) {
	var maxHeight = 0;

	for (var i = 0; i < cells.length; i++) {
		var cellHeight = this._getImageHeightFromNode(cells[i]);
		if (cellHeight > maxHeight) {
			maxHeight = cellHeight;
		}
	}

	return maxHeight;
};

/**
 * Gets the maximum estimated height from cells in a row.
 * Checks for measured heights (_height property) and content-based heights.
 *
 * @param {Array<object>} cells - Array of cell objects in a row.
 * @returns {number} The maximum estimated height found in the cells, or 0 if cannot estimate.
 */
 LayoutBuilder.prototype._getMaxCellHeight = function (cells) {
	var maxHeight = 0;

	for (var i = 0; i < cells.length; i++) {
		var cell = cells[i];
		if (!cell || cell._span) {
			continue; // Skip null cells and span placeholders
		}

		var cellHeight = 0;

		// Check if cell has measured height from docMeasure phase
		if (cell._height) {
			cellHeight = cell._height;
		}
		// Check for image content
		else if (cell.image && cell._maxHeight) {
			cellHeight = cell._maxHeight;
		}
		// Check for nested content with height
		else {
			cellHeight = this._getImageHeightFromNode(cell);
		}

		if (cellHeight > maxHeight) {
			maxHeight = cellHeight;
		}
	}

	return maxHeight;
};

/**
 * Recursively gets image height from a node.
 *
 * @param {object} node - The node to extract image height from.
 * @returns {number} The image height if found; otherwise, 0.
 */
 LayoutBuilder.prototype._getImageHeightFromNode = function (node) {
	if (!node) {
		return 0;
	}

	// Direct image node with height
	if (node.image && node._height) {
		return node._height;
	}

	var maxHeight = 0;

	// Check in stack
	if (isArray(node.stack)) {
		for (var i = 0; i < node.stack.length; i++) {
			var h = this._getImageHeightFromNode(node.stack[i]);
			if (h > maxHeight) {
				maxHeight = h;
			}
		}
	}

	// Check in columns
	if (isArray(node.columns)) {
		for (var j = 0; j < node.columns.length; j++) {
			var h2 = this._getImageHeightFromNode(node.columns[j]);
			if (h2 > maxHeight) {
				maxHeight = h2;
			}
		}
	}

	// Check in table
	if (node.table && isArray(node.table.body)) {
		for (var r = 0; r < node.table.body.length; r++) {
			if (isArray(node.table.body[r])) {
				for (var c = 0; c < node.table.body[r].length; c++) {
					var h3 = this._getImageHeightFromNode(node.table.body[r][c]);
					if (h3 > maxHeight) {
						maxHeight = h3;
					}
				}
			}
		}
	}

	return maxHeight;
};


/**
 * Retrieves the ending cell for a row span in case it exists in a specified table column.
 *
 * @param {Array<Array<object>>} tableBody - The table body, represented as a 2D array of cell objects.
 * @param {number} rowIndex - The index of the starting row for the row span.
 * @param {object} column - The column object containing row span information.
 * @param {number} columnIndex - The index of the column within the row.
 * @returns {object|null} The cell at the end of the row span if it exists; otherwise, `null`.
 * @throws {Error} If the row span extends beyond the total row count.
 */
LayoutBuilder.prototype._getRowSpanEndingCell = function (tableBody, rowIndex, column, columnIndex) {
	if (column.rowSpan && column.rowSpan > 1) {
		var endingRow = rowIndex + column.rowSpan - 1;
		if (endingRow >= tableBody.length) {
			throw new Error(`Row span for column ${columnIndex} (with indexes starting from 0) exceeded row count`);
		}
		return tableBody[endingRow][columnIndex];
	}

	return null;
};

LayoutBuilder.prototype.processRow = function ({ marginX = [0, 0], dontBreakRows = false, rowsWithoutPageBreak = 0, cells, widths, gaps, tableNode, tableBody, rowIndex, height, heightOffset = 0 }) {
	var self = this;
	var isUnbreakableRow = dontBreakRows || rowIndex <= rowsWithoutPageBreak - 1;
	var pageBreaks = [];
	var pageBreaksByRowSpan = [];
	var positions = [];
	var willBreakByHeight = false;
	var columnAlignIndexes = {};
	var hasInlineImage = false;
	widths = widths || cells;

	// Check if row contains inline images
	if (!isUnbreakableRow) {
		for (var cellIdx = 0; cellIdx < cells.length; cellIdx++) {
			if (self._containsInlineImage(cells[cellIdx])) {
				hasInlineImage = true;
				break;
			}
		}
	}

	// Check if row would cause page break and force move to next page first
	// This keeps the entire row together on the new page
	// Apply when: forcePageBreakForAllRows is enabled OR row has inline images

	// Priority for forcePageBreakForAllRows setting:
	// 1. Table-specific layout.forcePageBreakForAllRows
	// 2. Tables with footerGapCollect: 'product-items' (auto-enabled)
	// 3. Global footerGapOption.forcePageBreakForAllRows
	var tableLayout = tableNode && tableNode._layout;
	var footerGapOpt = self.writer.context()._footerGapOption;
	var shouldForcePageBreak = false;

	if (tableLayout && tableLayout.forcePageBreakForAllRows !== undefined) {
		// Table-specific setting takes precedence
		shouldForcePageBreak = tableLayout.forcePageBreakForAllRows === true;
	} 

	if (!isUnbreakableRow && (shouldForcePageBreak || hasInlineImage)) {
		var availableHeight = self.writer.context().availableHeight;

		// Calculate estimated height from actual cell content
		var estimatedHeight = height; // Use provided height if available

		if (!estimatedHeight) {
			// Try to get maximum cell height from measured content
			var maxCellHeight = self._getMaxCellHeight(cells);

			if (maxCellHeight > 0) {
				// Add padding for table borders and cell padding (approximate)
				// Using smaller padding to avoid overly conservative page break detection
				var tablePadding = 10; // Account for row padding and borders
				estimatedHeight = maxCellHeight + tablePadding;
			} else {
				// Fallback: use minRowHeight from table layout or global config if provided
				// Priority: table-specific layout > global footerGapOption > default 80
				// Using higher default (80px) to handle text rows with wrapping and multiple lines
				// This is conservative but prevents text rows from being split across pages
				var minRowHeight = (tableLayout && tableLayout.minRowHeight) || (footerGapOpt && footerGapOpt.minRowHeight) || 80;
				estimatedHeight = minRowHeight;
			}
		}

		// Apply heightOffset from table definition to adjust page break calculation
		// This allows fine-tuning of page break detection for specific tables
		// heightOffset is passed as parameter from processTable
		if (heightOffset) {
			estimatedHeight = (estimatedHeight || 0) + heightOffset;
		}

		// Check if row won't fit on current page
		// Strategy: Force break if row won't fit AND we're not too close to page boundary
		// "Too close" means availableHeight is very small (< 5px) - at that point forcing
		// a break would create a nearly-blank page
		var minSpaceThreshold = 5; // Only skip forced break if < 5px space left

		if (estimatedHeight > availableHeight && availableHeight > minSpaceThreshold) {
			var currentPage = self.writer.context().page;
			var currentY = self.writer.context().y;

			// Draw vertical lines to fill the gap from current position to page break
			// This ensures vertical lines extend all the way to the bottom of the page
			if (tableNode && tableNode._tableProcessor && rowIndex > 0) {
				tableNode._tableProcessor.drawVerticalLinesForForcedPageBreak(
					rowIndex,
					self.writer,
					currentY,
					currentY + availableHeight
				);
			}

			// Move to next page before processing row
			self.writer.context().moveDown(availableHeight);
			self.writer.moveToNextPage();

			// Track this page break so tableProcessor can draw borders correctly
			pageBreaks.push({
				prevPage: currentPage,
				prevY: currentY + availableHeight,
				y: self.writer.context().y,
				page: self.writer.context().page,
				forced: true  // Mark as forced page break
			});

			// Mark that this row should not break anymore
			isUnbreakableRow = true;
			dontBreakRows = true;
		}
	}

	// Check if row should break by height
	if (!isUnbreakableRow && height > self.writer.context().availableHeight) {
		willBreakByHeight = true;
	}

	// Use the marginX if we are in a top level table/column (not nested)
	const marginXParent = self.nestedLevel === 1 ? marginX : null;
	const _bottomByPage = tableNode ? tableNode._bottomByPage : null;
	this.writer.context().beginColumnGroup(marginXParent, _bottomByPage);

	for (var i = 0, l = cells.length; i < l; i++) {
		var cell = cells[i];

		// Page change handler

		this.tracker.auto('pageChanged', storePageBreakClosure, function () {
			var width = widths[i]._calcWidth;
			var leftOffset = self._colLeftOffset(i, gaps);
			// Check if exists and retrieve the cell that started the rowspan in case we are in the cell just after
			var startingSpanCell = self._findStartingRowSpanCell(cells, i);

			if (cell.colSpan && cell.colSpan > 1) {
				for (var j = 1; j < cell.colSpan; j++) {
					width += widths[++i]._calcWidth + gaps[i];
				}
			}

			// if rowspan starts in this cell, we retrieve the last cell affected by the rowspan
			const rowSpanEndingCell = self._getRowSpanEndingCell(tableBody, rowIndex, cell, i);
			if (rowSpanEndingCell) {
				// We store a reference of the ending cell in the first cell of the rowspan
				cell._endingCell = rowSpanEndingCell;
				cell._endingCell._startingRowSpanY = cell._startingRowSpanY;
			}

			// If we are after a cell that started a rowspan
			var endOfRowSpanCell = null;
			if (startingSpanCell && startingSpanCell._endingCell) {
				// Reference to the last cell of the rowspan
				endOfRowSpanCell = startingSpanCell._endingCell;
				// Store if we are in an unbreakable block when we save the context and the originalX
				if (self.writer.transactionLevel > 0) {
					endOfRowSpanCell._isUnbreakableContext = true;
					endOfRowSpanCell._originalXOffset = self.writer.originalX;
				}
			}

			// We pass the endingSpanCell reference to store the context just after processing rowspan cell
			self.writer.context().beginColumn(width, leftOffset, endOfRowSpanCell, heightOffset);

			if (!cell._span) {
				self.processNode(cell);
				self.writer.context().updateBottomByPage();
				addAll(positions, cell.positions);
				if (cell.verticalAlign && cell._verticalAlignIdx !== undefined) {
					columnAlignIndexes[i] = cell._verticalAlignIdx;
				}
			} else if (cell._columnEndingContext) {
				var discountY = 0;
				if (dontBreakRows) {
					// Calculate how many points we have to discount to Y when dontBreakRows and rowSpan are combined
					const ctxBeforeRowSpanLastRow = self.writer.writer.contextStack[self.writer.writer.contextStack.length - 1];
					discountY = ctxBeforeRowSpanLastRow.y - cell._startingRowSpanY;
				}
				var originalXOffset = 0;
				// If context was saved from an unbreakable block and we are not in an unbreakable block anymore
				// We have to sum the originalX (X before starting unbreakable block) to X
				if (cell._isUnbreakableContext && !self.writer.transactionLevel) {
					originalXOffset = cell._originalXOffset;
				}
				// row-span ending
				// Recover the context after processing the rowspanned cell
				self.writer.context().markEnding(cell, originalXOffset, discountY);
			}
		});
	}

	// Check if last cell is part of a span
	var endingSpanCell = null;
	var lastColumn = cells.length > 0 ? cells[cells.length - 1] : null;
	if (lastColumn) {
		// Previous column cell has a rowspan
		if (lastColumn._endingCell) {
			endingSpanCell = lastColumn._endingCell;
			// Previous column cell is part of a span
		} else if (lastColumn._span === true) {
			// We get the cell that started the span where we set a reference to the ending cell
			const startingSpanCell = this._findStartingRowSpanCell(cells, cells.length);
			if (startingSpanCell) {
				// Context will be stored here (ending cell)
				endingSpanCell = startingSpanCell._endingCell;
				// Store if we are in an unbreakable block when we save the context and the originalX
				if (this.writer.transactionLevel > 0) {
					endingSpanCell._isUnbreakableContext = true;
					endingSpanCell._originalXOffset = this.writer.originalX;
				}
			}
		}
	}

	// If content did not break page, check if we should break by height
	if (willBreakByHeight && !isUnbreakableRow && pageBreaks.length === 0) {
		this.writer.context().moveDown(this.writer.context().availableHeight);
		this.writer.moveToNextPage();
	}

	var bottomByPage = this.writer.context().completeColumnGroup(height, endingSpanCell);
	var rowHeight = this.writer.context().height;
	for (var colIndex = 0, columnsLength = cells.length; colIndex < columnsLength; colIndex++) {
		var columnNode = cells[colIndex];
		if (columnNode._span) {
			continue;
		}
		if (columnNode.verticalAlign && columnAlignIndexes[colIndex] !== undefined) {
			var alignEntry = self.verticalAlignItemStack[columnAlignIndexes[colIndex]];
			if (alignEntry && alignEntry.begin && alignEntry.begin.item) {
				alignEntry.begin.item.viewHeight = rowHeight;
				alignEntry.begin.item.nodeHeight = columnNode._height;
			}
		}
		if (columnNode.layers) {
			columnNode.layers.forEach(function (layer) {
				if (layer.verticalAlign && layer._verticalAlignIdx !== undefined) {
					var layerEntry = self.verticalAlignItemStack[layer._verticalAlignIdx];
					if (layerEntry && layerEntry.begin && layerEntry.begin.item) {
						layerEntry.begin.item.viewHeight = rowHeight;
						layerEntry.begin.item.nodeHeight = layer._height;
					}
				}
			});
		}
	}

	if (tableNode) {
		tableNode._bottomByPage = bottomByPage;
		// If there are page breaks in this row, update data with prevY of last cell
		this._updatePageBreaksData(pageBreaks, tableNode, rowIndex);
	}

	return {
		pageBreaksBySpan: pageBreaksByRowSpan,
		pageBreaks: pageBreaks,
		positions: positions
	};

	function storePageBreakClosure(data) {
		const startsRowSpan = cell.rowSpan && cell.rowSpan > 1;
		if (startsRowSpan) {
			data.rowSpan = cell.rowSpan;
		}
		data.rowIndex = rowIndex;
		self._storePageBreakData(data, startsRowSpan, pageBreaks, tableNode);
	}

};

// lists
LayoutBuilder.prototype.processList = function (orderedList, node) {
	var self = this,
		items = orderedList ? node.ol : node.ul,
		gapSize = node._gapSize;

	this.writer.context().addMargin(gapSize.width);

	var nextMarker;
	this.tracker.auto('lineAdded', addMarkerToFirstLeaf, function () {
		items.forEach(function (item) {
			nextMarker = item.listMarker;
			self.processNode(item);
			addAll(node.positions, item.positions);
		});
	});

	this.writer.context().addMargin(-gapSize.width);

	function addMarkerToFirstLeaf(line) {
		// I'm not very happy with the way list processing is implemented
		// (both code and algorithm should be rethinked)
		if (nextMarker) {
			var marker = nextMarker;
			nextMarker = null;

			if (marker.canvas) {
				var vector = marker.canvas[0];

				offsetVector(vector, -marker._minWidth, 0);
				self.writer.addVector(vector);
			} else if (marker._inlines) {
				var markerLine = new Line(self.pageSize.width);
				markerLine.addInline(marker._inlines[0]);
				markerLine.x = -marker._minWidth;
				markerLine.y = line.getAscenderHeight() - markerLine.getAscenderHeight();
				self.writer.addLine(markerLine, true);
			}
		}
	}
};

// tables
LayoutBuilder.prototype.processTable = function (tableNode) {
	this.nestedLevel++;
	var processor = new TableProcessor(tableNode);

	// Store processor reference for forced page break vertical line drawing
	tableNode._tableProcessor = processor;

	processor.beginTable(this.writer);

	var rowHeights = tableNode.table.heights;
	for (var i = 0, l = tableNode.table.body.length; i < l; i++) {
		// if dontBreakRows and row starts a rowspan
		// we store the 'y' of the beginning of each rowSpan
		if (processor.dontBreakRows) {
			tableNode.table.body[i].forEach(cell => {
				if (cell.rowSpan && cell.rowSpan > 1) {
					cell._startingRowSpanY = this.writer.context().y;
				}
			});
		}

		processor.beginRow(i, this.writer);

		var height;
		if (isFunction(rowHeights)) {
			height = rowHeights(i);
		} else if (isArray(rowHeights)) {
			height = rowHeights[i];
		} else {
			height = rowHeights;
		}

		if (height === 'auto') {
			height = undefined;
		}

		var heightOffset = tableNode.heightOffset != undefined ? tableNode.heightOffset : 0;

		var pageBeforeProcessing = this.writer.context().page;

		var result = this.processRow({
			marginX: tableNode._margin ? [tableNode._margin[0], tableNode._margin[2]] : [0, 0],
			dontBreakRows: processor.dontBreakRows,
			rowsWithoutPageBreak: processor.rowsWithoutPageBreak,
			cells: tableNode.table.body[i],
			widths: tableNode.table.widths,
			gaps: tableNode._offsets.offsets,
			tableBody: tableNode.table.body,
			tableNode,
			rowIndex: i,
			height,
			heightOffset
		});
		addAll(tableNode.positions, result.positions);

		if (!result.pageBreaks || result.pageBreaks.length === 0) {
			var breaksBySpan = tableNode && tableNode._breaksBySpan || null;
			var breakBySpanData = this._findSameRowPageBreakByRowSpanData(breaksBySpan, pageBeforeProcessing, i);
			if (breakBySpanData) {
				var finalBreakBySpanData = this._getPageBreakListBySpan(tableNode, breakBySpanData.prevPage, i);
				result.pageBreaks.push(finalBreakBySpanData);
			}
		}

		// Get next row cells for look-ahead page break detection
		var nextRowCells = (i + 1 < tableNode.table.body.length) ? tableNode.table.body[i + 1] : null;

		processor.endRow(i, this.writer, result.pageBreaks, nextRowCells, this);
	}

	processor.endTable(this.writer);
	this.nestedLevel--;
	if (this.nestedLevel === 0) {
		this.writer.context().resetMarginXTopParent();
	}
};

// leafs (texts)
LayoutBuilder.prototype.processLeaf = function (node) {
	var line = this.buildNextLine(node);
	if (line && (node.tocItem || node.id)) {
		line._node = node;
	}
	var currentHeight = (line) ? line.getHeight() : 0;
	var maxHeight = node.maxHeight || -1;

	if (line) {
		var nodeId = getNodeId(node);
		if (nodeId) {
			line.id = nodeId;
		}
	}

	if (node._tocItemRef) {
		line._pageNodeRef = node._tocItemRef;
	}

	if (node._pageRef) {
		line._pageNodeRef = node._pageRef._nodeRef;
	}

	if (line && line.inlines && isArray(line.inlines)) {
		for (var i = 0, l = line.inlines.length; i < l; i++) {
			if (line.inlines[i]._tocItemRef) {
				line.inlines[i]._pageNodeRef = line.inlines[i]._tocItemRef;
			}

			if (line.inlines[i]._pageRef) {
				line.inlines[i]._pageNodeRef = line.inlines[i]._pageRef._nodeRef;
			}
		}
	}

	while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
		var positions = this.writer.addLine(line);
		node.positions.push(positions);
		line = this.buildNextLine(node);
		if (line) {
			currentHeight += line.getHeight();
		}
	}
};

LayoutBuilder.prototype.processToc = function (node) {
	if (node.toc.title) {
		this.processNode(node.toc.title);
	}
	if (node.toc._table) {
		this.processNode(node.toc._table);
	}
};

LayoutBuilder.prototype.buildNextLine = function (textNode) {

	function cloneInline(inline) {
		var newInline = inline.constructor();
		for (var key in inline) {
			newInline[key] = inline[key];
		}
		return newInline;
	}

	if (!textNode._inlines || textNode._inlines.length === 0) {
		return null;
	}

	var line = new Line(this.writer.context().availableWidth);
	var textTools = new TextTools(null);

	while (textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
		var inline = textNode._inlines.shift();

		if (!inline.noWrap && inline.text.length > 1 && inline.width > line.maxWidth) {
			var widthPerChar = inline.width / inline.text.length;
			var maxChars = Math.floor(line.maxWidth / widthPerChar);
			if (maxChars < 1) {
				maxChars = 1;
			}
			if (maxChars < inline.text.length) {
				var newInline = cloneInline(inline);

				newInline.text = inline.text.substr(maxChars);
				inline.text = inline.text.substr(0, maxChars);

				newInline.width = textTools.widthOfString(newInline.text, newInline.font, newInline.fontSize, newInline.characterSpacing);
				inline.width = textTools.widthOfString(inline.text, inline.font, inline.fontSize, inline.characterSpacing);

				textNode._inlines.unshift(newInline);
			}
		}

		line.addInline(inline);
	}

	line.lastLineInParagraph = textNode._inlines.length === 0;

	return line;
};

// images
LayoutBuilder.prototype.processImage = function (node) {
	var position = this.writer.addImage(node);
	node.positions.push(position);
};

LayoutBuilder.prototype.processSVG = function (node) {
	var position = this.writer.addSVG(node);
	node.positions.push(position);
};

LayoutBuilder.prototype.processCanvas = function (node) {
	var height = node._minHeight;

	if (node.absolutePosition === undefined && this.writer.context().availableHeight < height) {
		// TODO: support for canvas larger than a page
		// TODO: support for other overflow methods

		this.writer.moveToNextPage();
	}

	this.writer.alignCanvas(node);

	node.canvas.forEach(function (vector) {
		var position = this.writer.addVector(vector);
		node.positions.push(position);
	}, this);

	this.writer.context().moveDown(height);
};

LayoutBuilder.prototype.processQr = function (node) {
	var position = this.writer.addQr(node);
	node.positions.push(position);
};

function processNode_test(node) {
	decorateNode(node);

	var prevTop = testWriter.context().getCurrentPosition().top;

	applyMargins(function () {
		var unbreakable = node.unbreakable;
		if (unbreakable) {
			testWriter.beginUnbreakableBlock();
		}

		var absPosition = node.absolutePosition;
		if (absPosition) {
			testWriter.context().beginDetachedBlock();
			testWriter.context().moveTo(absPosition.x || 0, absPosition.y || 0);
		}

		var relPosition = node.relativePosition;
		if (relPosition) {
			testWriter.context().beginDetachedBlock();
			if (typeof testWriter.context().moveToRelative === 'function') {
				testWriter.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
			} else if (currentLayoutBuilder && currentLayoutBuilder.writer) {
				testWriter.context().moveTo(
					(relPosition.x || 0) + currentLayoutBuilder.writer.context().x,
					(relPosition.y || 0) + currentLayoutBuilder.writer.context().y
				);
			}
		}

		var verticalAlignBegin;
		if (node.verticalAlign) {
			verticalAlignBegin = testWriter.beginVerticalAlign(node.verticalAlign);
		}

		if (node.stack) {
			processVerticalContainer_test(node);
		} else if (node.table) {
			processTable_test(node);
		} else if (node.text !== undefined) {
			processLeaf_test(node);
		}

		if (absPosition || relPosition) {
			testWriter.context().endDetachedBlock();
		}

		if (unbreakable) {
			testResult = testWriter.commitUnbreakableBlock_test();
		}

		if (node.verticalAlign) {
			testVerticalAlignStack.push({ begin: verticalAlignBegin, end: testWriter.endVerticalAlign(node.verticalAlign) });
		}
	});

	node._height = testWriter.context().getCurrentPosition().top - prevTop;

	function applyMargins(callback) {
		var margin = node._margin;

		if (node.pageBreak === 'before') {
			testWriter.moveToNextPage(node.pageOrientation);
		}

		if (margin) {
			testWriter.context().moveDown(margin[1]);
			testWriter.context().addMargin(margin[0], margin[2]);
		}

		callback();

		if (margin) {
			testWriter.context().addMargin(-margin[0], -margin[2]);
			testWriter.context().moveDown(margin[3]);
		}

		if (node.pageBreak === 'after') {
			testWriter.moveToNextPage(node.pageOrientation);
		}
	}
}

function processVerticalContainer_test(node) {
	node.stack.forEach(function (item) {
		processNode_test(item);
		addAll(node.positions, item.positions);
	});
}

function processTable_test(tableNode) {
	var processor = new TableProcessor(tableNode);
	processor.beginTable(testWriter);

	for (var i = 0, l = tableNode.table.body.length; i < l; i++) {
		processor.beginRow(i, testWriter);
		var result = processRow_test(tableNode.table.body[i], tableNode.table.widths, tableNode._offsets ? tableNode._offsets.offsets : null, tableNode.table.body, i);
		addAll(tableNode.positions, result.positions);
		processor.endRow(i, testWriter, result.pageBreaks);
	}

	processor.endTable(testWriter);
}

function processRow_test(columns, widths, gaps, tableBody, tableRow) {
	var pageBreaks = [];
	var positions = [];

	testTracker.auto('pageChanged', storePageBreakData, function () {
		widths = widths || columns;

		testWriter.context().beginColumnGroup();

		var verticalAlignCols = {};

		for (var i = 0, l = columns.length; i < l; i++) {
			var column = columns[i];
			var width = widths[i]._calcWidth || widths[i];
			var leftOffset = colLeftOffset(i);
			var colIndex = i;
			if (column.colSpan && column.colSpan > 1) {
				for (var j = 1; j < column.colSpan; j++) {
					width += (widths[++i]._calcWidth || widths[i]) + (gaps ? gaps[i] : 0);
				}
			}

			testWriter.context().beginColumn(width, leftOffset, getEndingCell(column, i));

			if (!column._span) {
				processNode_test(column);
				verticalAlignCols[colIndex] = testVerticalAlignStack.length - 1;
				addAll(positions, column.positions);
			} else if (column._columnEndingContext) {
				testWriter.context().markEnding(column);
			}
		}

		testWriter.context().completeColumnGroup();

		var rowHeight = testWriter.context().height;
		for (var c = 0, clen = columns.length; c < clen; c++) {
			var col = columns[c];
			if (col._span) {
				continue;
			}
			if (col.verticalAlign && verticalAlignCols[c] !== undefined) {
				var alignItem = testVerticalAlignStack[verticalAlignCols[c]].begin.item;
				alignItem.viewHeight = rowHeight;
				alignItem.nodeHeight = col._height;
			}
		}
	});

	return { pageBreaks: pageBreaks, positions: positions };

	function storePageBreakData(data) {
		var pageDesc;
		for (var idx = 0, len = pageBreaks.length; idx < len; idx++) {
			var desc = pageBreaks[idx];
			if (desc.prevPage === data.prevPage) {
				pageDesc = desc;
				break;
			}
		}

		if (!pageDesc) {
			pageDesc = data;
			pageBreaks.push(pageDesc);
		}
		pageDesc.prevY = Math.max(pageDesc.prevY, data.prevY);
		pageDesc.y = Math.min(pageDesc.y, data.y);
	}

	function colLeftOffset(i) {
		if (gaps && gaps.length > i) {
			return gaps[i];
		}
		return 0;
	}

	function getEndingCell(column, columnIndex) {
		if (column.rowSpan && column.rowSpan > 1) {
			var endingRow = tableRow + column.rowSpan - 1;
			if (endingRow >= tableBody.length) {
				throw new Error('Row span for column ' + columnIndex + ' (with indexes starting from 0) exceeded row count');
			}
			return tableBody[endingRow][columnIndex];
		}
		return null;
	}
}

function processLeaf_test(node) {
	var line = buildNextLine_test(node);
	var currentHeight = line ? line.getHeight() : 0;
	var maxHeight = node.maxHeight || -1;

	while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
		var positions = testWriter.addLine(line);
		node.positions.push(positions);
		line = buildNextLine_test(node);
		if (line) {
			currentHeight += line.getHeight();
		}
	}
}

function buildNextLine_test(textNode) {
	function cloneInline(inline) {
		var newInline = inline.constructor();
		for (var key in inline) {
			newInline[key] = inline[key];
		}
		return newInline;
	}

	if (!textNode._inlines || textNode._inlines.length === 0) {
		return null;
	}

	var line = new Line(testWriter.context().availableWidth);
	var textTools = new TextTools(null);

	while (textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
		var inline = textNode._inlines.shift();

		if (!inline.noWrap && inline.text.length > 1 && inline.width > line.maxWidth) {
			var widthPerChar = inline.width / inline.text.length;
			var maxChars = Math.floor(line.maxWidth / widthPerChar);
			if (maxChars < 1) {
				maxChars = 1;
			}
			if (maxChars < inline.text.length) {
				var newInline = cloneInline(inline);

				newInline.text = inline.text.substr(maxChars);
				inline.text = inline.text.substr(0, maxChars);

				newInline.width = textTools.widthOfString(newInline.text, newInline.font, newInline.fontSize, newInline.characterSpacing);
				inline.width = textTools.widthOfString(inline.text, inline.font, inline.fontSize, inline.characterSpacing);

				textNode._inlines.unshift(newInline);
			}
		}

		line.addInline(inline);
	}

	line.lastLineInParagraph = textNode._inlines.length === 0;

	return line;
}

module.exports = LayoutBuilder;
