/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

/**
 * Removes indentation from content preserving the relative indentation within the content.
 * @param content The content to remove indentation from
 * @returns Content with common indentation removed
 */
module.exports = function removeIndentation( content ) {
	// Remove unwanted indentation.
	const lines = content.split( /\n/ );

	// Skip empty lines when detecting indentation level
	let indentationLine = 1;
	while ( indentationLine < lines.length && !lines[ indentationLine ].trim() ) {
		indentationLine++;
	}

	// Get the indentation of the first non-empty line, or empty string if no valid lines
	const indentation = indentationLine < lines.length ? lines[ indentationLine ].match( /^\s*/ )[ 0 ] : '';

	if ( !indentation ) {
		return content.trim();
	}

	let pattern;

	// When using spaces as indentation, some editors may mix them with tabs.
	// In such case, let's try to remove tabs as well. 4 spaces are treat as a single tab character.
	if ( indentation[ 0 ] === ' ' ) {
		pattern = new RegExp( `^${ indentation }|${ '\\t'.repeat( Math.ceil( indentation.length / 4 ) ) }` );
	} else {
		pattern = new RegExp( `^${ indentation }` );
	}

	// Process each line to remove common indentation
	content = lines.map( line => line.replace( pattern, '' ) ).join( '\n' );

	// Remove first linebreak and last linebreak.
	content = content.replace( /^\n/, '' );
	content = content.replace( /\n$/, '' );

	return content;
};
