const findMinMaxAndTicksForRecharts = (compareValues: number[]) => {
	// Calculate min and max data values
	const dataMin = Math.min(...compareValues);
	const dataMax = Math.max(...compareValues);

	// Determine domain bounds
	let minY: number;
	let maxY: number;

	if (dataMin >= 0) {
		// All positive
		minY = dataMin;
		maxY = Math.ceil(dataMax * 1.2);
	} else if (dataMax <= 0) {
		// All negative
		minY = Math.floor(dataMin * 1.2);
		maxY = dataMax;
	} else {
		// Data spans negative and positive
		minY = Math.floor(dataMin);
		maxY = Math.ceil(dataMax);
	}

	const numberOfSegments = 8;
	let ticks;

	if (dataMin >= 0) {
		// All positive: start ticks at 0
		const step = (maxY - 0) / numberOfSegments;
		ticks = Array.from({ length: numberOfSegments + 1 }, (_, i) => Math.round(0 + i * step));
		// Ensure 0 is included
		if (!ticks.includes(0)) {
			ticks.unshift(0);
		}
	} else if (dataMax <= 0) {
		// All negative: start ticks at 0
		const step = (maxY - minY) / numberOfSegments;
		ticks = Array.from({ length: numberOfSegments + 1 }, (_, i) => Math.round(minY + i * step));
		// Ensure 0 is included
		if (!ticks.includes(0)) {
			ticks.unshift(0);
		}
	} else {
		// Spanning zero: generate balanced ticks around zero
		const lowerStep = Math.abs(minY) / Math.floor(numberOfSegments / 2);
		const upperStep = Math.abs(maxY) / Math.ceil(numberOfSegments / 2);

		const lowerTicks = Array.from({ length: Math.floor(numberOfSegments / 2) + 1 }, (_, i) =>
			Math.round(minY + i * lowerStep)
		);
		const upperTicks = Array.from({ length: Math.ceil(numberOfSegments / 2) + 1 }, (_, i) =>
			Math.round(0 + i * upperStep)
		);

		// Combine and remove duplicates
		ticks = [...lowerTicks, ...upperTicks].filter(
			(value, index, self) => self.indexOf(value) === index
		);
		// Sort the ticks
		ticks.sort((a, b) => a - b);

		// Make sure 0 is included
		if (!ticks.includes(0)) {
			// Insert 0 into the sorted array at the correct position
			const index = ticks.findIndex((tick) => tick > 0);
			if (index === -1) {
				ticks.push(0);
			} else {
				ticks.splice(index, 0, 0);
			}
		}
	}

	// Also, ensure minY and maxY are consistent with the data span
	minY = Math.min(minY, 0);
	maxY = Math.max(maxY, 0);

	return { minY, maxY, ticks };
};

export default findMinMaxAndTicksForRecharts;
