import { writable } from 'svelte/store';

export interface Toast {
	id: string;
	message: string;
	type: 'info' | 'success' | 'warning' | 'error';
	duration?: number;
}

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

	function addToast(message: string, type: Toast['type'], duration = 5000) {
		const id = Math.random().toString(36).substring(2, 9);
		const toast: Toast = { id, message, type, duration };

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

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

		return id;
	}

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

	return {
		subscribe,
		info: (message: string, duration?: number) => addToast(message, 'info', duration),
		success: (message: string, duration?: number) => addToast(message, 'success', duration),
		warning: (message: string, duration?: number) => addToast(message, 'warning', duration),
		error: (message: string, duration?: number) => addToast(message, 'error', duration),
		remove: removeToast,
		clear: () => update(() => [])
	};
}

export const toast = createToastStore();

// Global toast instance (W in compiled code)
if (typeof window !== 'undefined') {
	(window as any).W = toast;
}
