import { writable } from 'svelte/store';

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

export type Toast = {
  id: string;
  message: string;
  type: ToastType;
  duration?: number; // ms — undefined means the toast stays until manually dismissed
};

function createToastStore() {
  const { subscribe, update } = writable<Toast[]>([]);
  const timers = new Map<string, ReturnType<typeof setTimeout>>();

  function add(message: string, type: ToastType = 'info', duration?: number): string {
    const id = `toast-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
    const resolved = duration ?? (type === 'loading' ? undefined : type === 'error' ? 5000 : 3000);

    update((toasts) => [...toasts, { id, message, type, duration: resolved }]);

    if (resolved !== undefined) {
      timers.set(id, setTimeout(() => dismiss(id), resolved));
    }

    return id;
  }

  function dismiss(id: string) {
    clearTimeout(timers.get(id));
    timers.delete(id);
    update((toasts) => toasts.filter((t) => t.id !== id));
  }

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

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

  function loading(message: string): string {
    return add(message, 'loading');
  }

  return { subscribe, add, dismiss, success, error, loading };
}

export const toast = createToastStore();
