import { ce } from 'morphux';

/**
 * A linear interpolation helper function.
 * @param a The start value.
 * @param b The end value.
 * @param t The interpolation factor (0 to 1).
 * @returns The interpolated value.
 */
export const lerp = (a: number, b: number, t: number): number =>
	a + (b - a) * t;

export const setStatusState = (
	statusElement: HTMLDivElement,
	state: StatusType
) => {
	statusElement.classList.remove(
		'ntsh_status-green',
		'ntsh_status-yellow',
		'ntsh_status-red',
		'ntsh_status-gray'
	);
	statusElement.classList.add(`ntsh_status-${state}`);
};
export type StatusType = 'green' | 'yellow' | 'red' | 'gray';

export const setProgressState = (
	progressElement: HTMLDivElement,
	value: number,
	min: number,
	max: number,
	unit: string
) => {
	const percentage = (value - min) / (max - min);

	const progressValue: HTMLDivElement = progressElement.querySelector(
		'.ntsh_progress-value'
	);
	progressValue.style.width = `${percentage * 100}%`;

	const label: HTMLDivElement = progressElement.querySelector(
		'.ntsh_progress-label'
	);
	label.innerText = `${value}${unit}`;
};

export const createProgress = (
	value: number,
	min: number,
	max: number,
	unit: string
) => {
	const progress = ce('div', 'ntsh_progress');
	progress.appendChild(ce('div', 'ntsh_progress-value'));
	progress.appendChild(ce('div', 'ntsh_progress-label'));
	setProgressState(progress, value, min, max, unit);
	return progress;
};
export function capitalizeFirstLetter(string: string) {
	return string.charAt(0).toUpperCase() + string.slice(1);
}

export type ServiceState =
	| 'CONNECTING'
	| 'CONNECTED'
	| 'DISCONNECTED'
	| 'FAILED';

export function formatUptime(seconds: number): string {
	if (seconds < 0) return '';
	const days = Math.floor(seconds / 86400);
	seconds %= 86400;
	const hours = Math.floor(seconds / 3600);
	seconds %= 3600;
	const minutes = Math.floor(seconds / 60);
	seconds = Math.floor(seconds % 60);

	const parts = [];
	if (days > 0) parts.push(`${days}d`);

	parts.push(
		`${hours.toString().padStart(2, '0')}:${minutes
			.toString()
			.padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
	);
	return parts.join(' ');
}

export function delay(duration: number) {
	return new Promise((resolve) => setTimeout(resolve, duration));
}
