import { writable } from 'svelte/store';

export type ToastKind = 'info' | 'success' | 'error';

export interface ToastItem {
	id: number;
	message: string;
	kind: ToastKind;
}

let seq = 0;
export const toasts = writable<ToastItem[]>([]);

export function pushToast(message: string, kind: ToastKind = 'info', ms = 3200): void {
	const id = ++seq;
	toasts.update((list) => [...list, { id, message, kind }]);
	if (ms > 0) {
		setTimeout(() => {
			toasts.update((list) => list.filter((t) => t.id !== id));
		}, ms);
	}
}

export function dismissToast(id: number): void {
	toasts.update((list) => list.filter((t) => t.id !== id));
}

export function toastSuccess(message: string): void {
	pushToast(message, 'success');
}

export function toastError(message: string): void {
	pushToast(message, 'error', 5000);
}
