import { create } from "zustand";

export type ToastType = "success" | "error" | "info" | "warning";

interface Toast {
  id: string;
  message: string;
  type: ToastType;
}

interface ToastStore {
  toasts: Toast[];
  addToast: (message: string, type?: ToastType) => void;
  removeToast: (id: string) => void;
}

let nextId = 0;

export const useToast = create<ToastStore>((set) => ({
  toasts: [],
  addToast: (message, type = "info") => {
    const id = String(nextId++);
    set((state) => ({ toasts: [...state.toasts, { id, message, type }] }));
    // Auto-dismiss after 4 seconds
    setTimeout(() => {
      set((state) => ({ toasts: state.toasts.filter((t) => t.id !== id) }));
    }, 4000);
  },
  removeToast: (id) => {
    set((state) => ({ toasts: state.toasts.filter((t) => t.id !== id) }));
  },
}));

const typeStyles: Record<ToastType, { bg: string; border: string; icon: string }> = {
  success: {
    bg: "bg-[var(--color-success)]/10",
    border: "border-[var(--color-success)]/40",
    icon: "✓",
  },
  error: {
    bg: "bg-[var(--color-danger)]/10",
    border: "border-[var(--color-danger)]/40",
    icon: "✕",
  },
  info: {
    bg: "bg-[var(--color-gold-bright)]/10",
    border: "border-[var(--color-gold-bright)]/40",
    icon: "ℹ",
  },
  warning: {
    bg: "bg-[var(--color-gold-muted)]/10",
    border: "border-[var(--color-gold-muted)]/40",
    icon: "⚠",
  },
};

export function ToastContainer() {
  const { toasts, removeToast } = useToast();

  return (
    <div className="fixed top-4 right-4 z-50 flex flex-col gap-2 pointer-events-none">
      {toasts.map((toast) => {
        const style = typeStyles[toast.type];
        return (
          <div
            key={toast.id}
            className={`pointer-events-auto glass-card px-4 py-3 flex items-center gap-2 text-sm ${style.bg} border ${style.border} animate-[slideIn_0.2s_ease-out]`}
          >
            <span className="text-base">{style.icon}</span>
            <span className="text-[var(--color-text-primary)]">{toast.message}</span>
            <button
              onClick={() => removeToast(toast.id)}
              className="ml-2 text-[var(--color-text-dim)] hover:text-[var(--color-text-primary)] cursor-pointer"
            >
              ×
            </button>
          </div>
        );
      })}
    </div>
  );
}