import { writable } from 'svelte/store';

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

export interface Toast {
	id: string;
	message: string;
	type: ToastType;
	duration: number;
}

function createToastStore() {
	const { subscribe, update } = writable<Toast[]>([]);

	let counter = 0;

	function add(message: string, type: ToastType = 'info', duration = 5000): string {
		const id = `toast-${++counter}-${Date.now()}`;
		const toast: Toast = { id, message, type, duration };

		update((toasts) => [...toasts, toast]);

		if (duration > 0) {
			setTimeout(() => remove(id), duration);
		}

		return id;
	}

	function remove(id: string): void {
		update((toasts) => toasts.filter((t) => t.id !== id));
	}

	function success(message: string, duration = 5000): string {
		return add(message, 'success', duration);
	}

	function error(message: string, duration = 7000): string {
		return add(message, 'error', duration);
	}

	function warning(message: string, duration = 5000): string {
		return add(message, 'warning', duration);
	}

	function info(message: string, duration = 5000): string {
		return add(message, 'info', duration);
	}

	return {
		subscribe,
		add,
		remove,
		success,
		error,
		warning,
		info
	};
}

export const toasts = createToastStore();
