import { create } from 'zustand';

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

export interface Toast {
  id: number;
  kind: ToastKind;
  message: string;
  /** Optional action label + handler (e.g. "Undo"). */
  action?: { label: string; onClick: () => void };
  /** Auto-dismiss timeout in ms. 0 keeps it until dismissed. */
  ttl: number;
}

interface ToastState {
  toasts: Toast[];
  push: (t: Omit<Toast, 'id'> & { id?: number }) => number;
  dismiss: (id: number) => void;
}

let nextId = 1;

export const useToastStore = create<ToastState>((set, get) => ({
  toasts: [],
  push: ({ id, ...rest }) => {
    const toastId = id ?? nextId++;
    const toast: Toast = { id: toastId, ...rest };
    set((s) => ({ toasts: [...s.toasts, toast] }));
    if (toast.ttl > 0) {
      setTimeout(() => get().dismiss(toastId), toast.ttl);
    }
    return toastId;
  },
  dismiss: (id) => set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
}));

/** Convenience helpers for the common kinds. */
export const toast = {
  success: (message: string, opts: Partial<Omit<Toast, 'id' | 'kind' | 'message'>> = {}) =>
    useToastStore.getState().push({ kind: 'success', message, ttl: 4000, ...opts }),
  error: (message: string, opts: Partial<Omit<Toast, 'id' | 'kind' | 'message'>> = {}) =>
    useToastStore.getState().push({ kind: 'error', message, ttl: 6000, ...opts }),
  info: (message: string, opts: Partial<Omit<Toast, 'id' | 'kind' | 'message'>> = {}) =>
    useToastStore.getState().push({ kind: 'info', message, ttl: 4000, ...opts }),
};
