import { create } from "zustand";
import type { ToastItem, ToastVariant } from "@/components/ui/toast";

interface ToastStore {
  toasts: ToastItem[];
  add: (toast: Omit<ToastItem, "id">) => void;
  dismiss: (id: string) => void;
}

export const useToastStore = create<ToastStore>((set) => ({
  toasts: [],

  add: (toast) => {
    const id = Math.random().toString(36).slice(2);
    set((s) => {
      const alreadyVisible = s.toasts.some(
        (t) =>
          t.variant === toast.variant &&
          t.title === toast.title &&
          t.description === toast.description
      );

      if (alreadyVisible) return s;

      return { toasts: [...s.toasts, { ...toast, id }].slice(-4) };
    });
  },

  dismiss: (id) =>
    set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
}));

// Convenience hook — call from any client component
export function useToast() {
  const add = useToastStore((s) => s.add);

  return {
    success: (title: string, description?: string) =>
      add({ variant: "success", title, description }),

    error: (title: string, description?: string) =>
      add({ variant: "error", title, description }),

    warning: (title: string, description?: string) =>
      add({ variant: "warning", title, description }),

    info: (title: string, description?: string) =>
      add({ variant: "info", title, description }),

    toast: (variant: ToastVariant, title: string, description?: string) =>
      add({ variant, title, description }),
  };
}
