import { writable } from 'svelte/store';

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

type ToastItem = {
  id: string;
  type: ToastType;
  message: string;
  timeout?: number;
};

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

function uid(): string {
  return Math.random().toString(36).slice(2) + Date.now().toString(36);
}

function show(message: string, type: ToastType = 'info', timeout = 2500): string {
  const id = uid();
  toasts.update((list) => [...list, { id, type, message, timeout }]);
  if (timeout > 0) {
    setTimeout(() => dismiss(id), timeout);
  }
  return id;
}

export function success(message: string, timeout = 2500): string {
  return show(message, 'success', timeout);
}

export function error(message: string, timeout = 3500): string {
  return show(message, 'error', timeout);
}

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