export type ToastType = 'success' | 'error' | 'warning' | 'info';

export interface ToastItem {
	id: string;
	type: ToastType;
	message: string;
	leaving?: boolean;
}

let toasts = $state<ToastItem[]>([]);

export function getToasts() {
	return toasts;
}

export function showToast(options: {
	message: string;
	type?: ToastType;
	duration?: number;
}) {
	const message = options.message.trim();
	if (!message) return;

	const id = crypto.randomUUID();
	const type = options.type ?? 'info';
	const duration = options.duration ?? 3200;

	toasts = [...toasts, { id, type, message }];

	setTimeout(() => dismissToast(id), duration);
}

export function dismissToast(id: string) {
	if (!toasts.some((item) => item.id === id && !item.leaving)) return;

	toasts = toasts.map((item) => (item.id === id ? { ...item, leaving: true } : item));

	setTimeout(() => {
		toasts = toasts.filter((item) => item.id !== id);
	}, 220);
}
