function normalizeRawMountValue(rawValue) {
	let value = String(rawValue ?? '').trim();
	if (!value) {
		return '';
	}

	value = value.replace(/\s+/g, '');
	const hasComma = value.includes(',');
	const hasDot = value.includes('.');

	if (hasComma && hasDot) {
		if (value.lastIndexOf('.') > value.lastIndexOf(',')) {
			// Formato tipo en-US: 12,345.67 -> 12345,67
			value = value.replace(/,/g, '');
			const lastDotIndex = value.lastIndexOf('.');
			value = `${value.slice(0, lastDotIndex).replace(/\./g, '')},${value.slice(lastDotIndex + 1)}`;
		} else {
			// Formato es-VE: 12.345,67 -> 12345,67
			value = value.replace(/\./g, '');
		}
	} else if (hasDot && !hasComma) {
		const lastDotIndex = value.lastIndexOf('.');
		const decimalPart = value.slice(lastDotIndex + 1);

		if (decimalPart.length > 0 && decimalPart.length <= 2) {
			// Caso típico tras old input: 20000.00 -> 20000,00
			value = `${value.slice(0, lastDotIndex).replace(/\./g, '')},${decimalPart}`;
		} else {
			value = value.replace(/\./g, '');
		}
	}

	return value;
}

function formatMountValue(rawValue, keepTrailingComma = false) {
	const normalizedRaw = normalizeRawMountValue(rawValue);
	const sanitized = normalizedRaw.replace(/[^\d,]/g, '');
	const commaIndex = sanitized.indexOf(',');

	let integerPart = sanitized;
	let decimalPart = '';

	if (commaIndex !== -1) {
		integerPart = sanitized.slice(0, commaIndex);
		decimalPart = sanitized.slice(commaIndex + 1).replace(/,/g, '').slice(0, 2);
	}

	const normalizedInteger = (integerPart || '0').replace(/^0+(?=\d)/, '');
	const withThousandSeparators = normalizedInteger.replace(/\B(?=(\d{3})+(?!\d))/g, '.');

	if (commaIndex !== -1) {
		return `${withThousandSeparators},${decimalPart}`;
	}

	if (keepTrailingComma) {
		return `${withThousandSeparators},`;
	}

	return withThousandSeparators;
}

function forceNumericCurrencyInput(input) {
	input.addEventListener('input', () => {
		const hasTrailingComma = input.value.endsWith(',');
		input.value = formatMountValue(input.value, hasTrailingComma);
	});

	input.addEventListener('blur', () => {
		if (!input.value) {
			return;
		}

		const [integerPart, decimalPart = ''] = input.value.split(',');
		const normalizedDecimal = decimalPart.padEnd(2, '0').slice(0, 2);
		input.value = `${integerPart},${normalizedDecimal}`;
	});
}

document.addEventListener('DOMContentLoaded', () => {
	const mountInputs = document.querySelectorAll('.mountFormat');

	mountInputs.forEach((input) => {
		forceNumericCurrencyInput(input);

		if (input.value) {
			input.value = formatMountValue(input.value);
		}
	});
});
