export function titleCase(text) {
	var value = String(text).replace(/\./g, ' ')
		.replace(/\s/g, ' ')
		.replace(/^(.)/, function ($1) { return $1.toUpperCase(); })
	// .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })

	return value
}

export function roundMath(number, decimalPlaces) {
	const factorOfTen = Math.pow(10, decimalPlaces)
	return Math.round(number * factorOfTen) / factorOfTen
}

export function fixNumber(num, decimalCount = 2) {
	const output = Math.round((num + Number.EPSILON) * (Math.pow(10, decimalCount))) / (Math.pow(10, decimalCount))
	return output
}

export function downloadFileBlob(fileName, blobData) {
	const url = window.URL.createObjectURL(blobData)
	const a = document.createElement('a')
	a.href = url
	a.download = fileName
	document.body.appendChild(a)
	a.click()
	a.remove()
	window.URL.revokeObjectURL(url)
}

/**
 * @param {Object} location - Objek location dari props (this.props.location)
 * @param {string} paramName - Nama key yang ingin diambil (misal: 'month')
 * @param {any} defaultValue - Nilai kembalian jika data null/undefined
 */
export const getStateParam = (location, paramName = null, defaultValue = null) => {
	if (!paramName) {
		return location?.state ?? defaultValue;
	}

	return location?.state?.[paramName] ?? defaultValue;
};

export const formatters = {
	// Untuk format Infinity
	infinity: {
		month: (val) => String(val === undefined || val === 'Infinity' || val === '-Infinity'
			? "0.0"
			: Number(val).toFixed(2)),
		totalCY: (val) => String(val === undefined || val === 'Infinity' || val === '-Infinity'
			? "0.0"
			: Number(val).toFixed(2)),
		totalOther: (val) => String(val !== '' && val !== 'Infinity' && val !== '-Infinity'
			? Number(val).toFixed(2)
			: val)
	},

	// Untuk format .value property
	value: {
		month: (val) => String(val?.value === undefined ? val : Number(val.value).toFixed(1)),
		total: (val) => String(val !== '' ? Number(val).toFixed(1) : val)
	}
};

// ===== HELPER FUNCTIONS =====
export const createMonthData = (item, startIdx, formatFn) => {
	const monthNames = ['january', 'february', 'march', 'april', 'may', 'june',
		'july', 'august', 'september', 'october', 'november', 'december'];

	const months = {};
	monthNames.forEach((month, idx) => {
		months[month] = formatFn(item[startIdx + idx]);
	});
	return months;
};

export const convertSelect = (id, name) => {
	const obj = id ? {
		id,
		name,
	} : null
	return obj
};